Script: Fivem Car Key

-- Give a car key to a player RegisterNetEvent('carkeys:giveKey') AddEventHandler('carkeys:giveKey', function(plate, targetId) local src = source local xPlayer = Framework.GetPlayerFromId(src) local targetPlayer = Framework.GetPlayerFromId(targetId)

-- Key item name (create this in your database/items) Config.KeyItem = 'car_key' fivem car key script

client_scripts { 'config.lua', 'client.lua' } -- Give a car key to a player

-- Notification style Config.Notify = function(msg, type) -- type: 'info', 'error', 'success' -- Change this to your framework's notification if Config.Framework == 'esx' then ESX.ShowNotification(msg) elseif Config.Framework == 'qb' then QBCore.Functions.Notify(msg, type) else print(msg) end end type) -- type: 'info'

-- Remove key from player (when vehicle is sold/destroyed) RegisterNetEvent('carkeys:removeKey') AddEventHandler('carkeys:removeKey', function(plate) local src = source local xPlayer = Framework.GetPlayerFromId(src) local keyItem = string.format('%s_%s', Config.KeyItem, plate) xPlayer.removeInventoryItem(keyItem, 1) end)

-- Block vehicle start without key (prevent hotwiring) Citizen.CreateThread(function() while true do Citizen.Wait(100) local ped = PlayerPedId() if IsPedInAnyVehicle(ped, false) then local vehicle = GetVehiclePedIsIn(ped, false) local plate = GetVehicleNumberPlateText(vehicle) lib.callback.await('carkeys:hasKey', false, plate) if not hasKey and GetPedInVehicleSeat(vehicle, -1) == ped then SetVehicleEngineOn(vehicle, false, false, true) Citizen.Wait(500) end end end end) Add this item to your items table:

-- Get vehicle from player's last entered Citizen.CreateThread(function() while true do Citizen.Wait(1000) local ped = PlayerPedId() if IsPedInAnyVehicle(ped, false) then local vehicle = GetVehiclePedIsIn(ped, false) if vehicle ~= currentVehicle then currentVehicle = vehicle local plate = GetVehicleNumberPlateText(vehicle) -- Check if player has key lib.callback.await('carkeys:hasKey', false, plate) hasKey = result if not hasKey then Config.Notify('You do not have the key for this vehicle!', 'error') -- Eject player from driver seat if GetPedInVehicleSeat(vehicle, -1) == ped then TaskLeaveVehicle(ped, vehicle, 0) end else vehicleLocked = false Config.Notify('You have the key for this vehicle', 'success') end end else currentVehicle = nil engineOn = false end end end)