# Player Data

## Overview

`Player.PlayerData` is authoritative server-side character state. The client receives a synchronized
view for presentation. This reference is scoped to the pinned source in **Sources**. It is not a
claim that every QBCore fork exposes the same fields or methods, nor an in-game test report.

![QBCore PlayerData lifecycle and synchronization](/diagrams/player-lifecycle.svg)

*Conceptual diagram; verify the behavior against your installed resource version.*

## Accessing Player Data

### Server-Side

```lua
local QBCore = exports['qb-core']:GetCoreObject()
local Player = QBCore.Functions.GetPlayer(source)
if not Player then return end
print(Player.PlayerData.citizenid)
```

Capture `local src = source` before yielding inside a network handler. After asynchronous work,
resolve the Player again and verify the same `citizenid`; the connection or character may have changed.

### Client-Side

```lua
local QBCore = exports['qb-core']:GetCoreObject()
local data = QBCore.Functions.GetPlayerData()
if data and data.citizenid and data.job then
    print(data.job.name)
end
```

Do not read `data.job.name` unconditionally while the character is still loading. See the lifecycle
pattern below for both normal login and a resource restarted after login.

## Player Data Structure

### Core Information

| Field | Meaning and boundary |
| --- | --- |
| `source` | Current server connection ID; not a persistent character key |
| `license` | License identifier used for the login ownership check |
| `citizenid` | Persistent character identifier |
| `cid` | Character-slot data; do not treat it as the server connection ID |
| `charinfo` | Character identity fields; available keys depend on the character system |
| `money` | Account balances owned by core money methods |
| `job`, `gang` | Resolved shared definition and grade data |
| `metadata` | Core and resource-defined character state |
| `items` | Inventory state loaded through the deployed inventory integration |
| `position` | Saved position data, not a live teleport API |

This is a field guide, not a complete default record to insert into SQL. Do not copy example money,
identity or metadata defaults into an existing character database.

## Common Player Data Operations

### Character Information

There is no `SetCharinfo` player method in the pinned method table. For an authorized server-side
operation, copy the existing table, validate the field being changed, and call `SetPlayerData`:

```lua
local function UpdatePhone(Player, phone)
    if type(phone) ~= 'string' or #phone < 3 or #phone > 32 then return false end
    local charinfo = {}
    for key, value in pairs(Player.PlayerData.charinfo) do
        charinfo[key] = value
    end
    charinfo.phone = phone
    Player.Functions.SetPlayerData('charinfo', charinfo)
    return true
end
```

This helper only validates shape. Its caller must authorize the operation and honor the phone
system's uniqueness/storage rules. It is not an unrestricted player-facing change-phone endpoint.

### Money Management

```lua
-- Inside an authorized server operation, after resolving Player.
local paid = Player.Functions.RemoveMoney('cash', 50, 'example-purchase')
if not paid then return end
```

`AddMoney`, `RemoveMoney`, `SetMoney` and `GetMoney` are player methods. Account names, limits and
negative-balance rules come from configuration. A successful debit is not an atomic inventory
purchase: check inventory capacity and define recovery before combining systems. Never accept a
client-selected price or directly edit `PlayerData.money` to bypass core methods.

### Job and Gang Management

```lua
-- Authorized server code only. Validate the selected shared definition and grade first.
Player.Functions.SetJob('police', 0)
Player.Functions.SetGang('ballas', 0)
Player.Functions.SetJobDuty(true)
```

At this pinned revision, `SetJob` writes salary to **`job.grade.payment`**, grade rank to
`job.grade.level`, and boss flags to `job.grade.isboss` and `job.isboss`. Some older layouts put
salary at `job.payment`; do not conflate them. `SetJob` may use fallback grade values, so validate
`QBCore.Shared.Jobs[name].grades[tostring(grade)]` before calling it.

### Metadata Management

```lua
-- Authorized server code; choose a resource-owned key and an allowed range.
local current = tonumber(Player.PlayerData.metadata.delivery_rep) or 0
Player.Functions.SetMetaData('delivery_rep', math.min(1000, current + 1))
```

The pinned core has `SetMetaData` and `GetMetaData`, not a general `AddMetaData` player method.
`AddRep` is a separate operation on the `metadata.rep` namespace. Read/modify/write is not a
cross-resource transaction; designate one owner for a field and avoid yielding between these steps.

### Item Management

Core loads inventory through the configured integration. Do not assume `AddItem`, `RemoveItem`,
`GetItemsByName` or `ClearInventory` are methods supplied by this core's Player class. Use the
inventory resource's supported exports and check their return values.

See [qb-inventory](/docs/resources/qb-inventory),
[server-confirmed usable items](/docs/guides/item-use-effect), and
[inventory API differences](/docs/troubleshooting/inventory-updates).

For an array of matching stacks, `#stacks` counts stacks, **not individual items**. Quantity is the
sum of each stack's `amount`, subject to the actual inventory return shape.

### Position Management

There is no `SetPosition` player method in the pinned method table. Updating a saved `position`
field does not move the entity. Use the appropriate authorized movement workflow and let your
framework's save path capture the resulting position. See [OneSync](/docs/advanced/onesync).

## Current Player method surface

The server Player object binds the following methods at this source baseline. Call bound methods as
`Player.Functions.Method(...)`.

| Method | Signature | Return / behavior |
| --- | --- | --- |
| `GetPlayerData` | `GetPlayerData()` | Current `PlayerData` table |
| `UpdateClient` | `UpdateClient(key, val)` | Synchronizes one field or a full snapshot; no return |
| `UpdatePlayerData` | alias of `UpdateClient` | Compatibility alias |
| `SetJob` | `SetJob(job, grade)` | Boolean success |
| `SetGang` | `SetGang(gang, grade)` | Boolean success |
| `Notify` | `Notify(text, notifyType, length)` | Sends `QBCore:Notify`; no return |
| `HasItem` | `HasItem(items, amount)` | Boolean inventory check |
| `GetName` | `GetName()` | Character display name |
| `SetJobDuty` | `SetJobDuty(onDuty)` | Updates duty state; no meaningful return |
| `SetPlayerData` | `SetPlayerData(key, val)` | Updates a top-level field; no meaningful return |
| `SetMetaData` | `SetMetaData(meta, val)` | Updates one metadata key; no meaningful return |
| `GetMetaData` | `GetMetaData(meta)` | Metadata value |
| `AddRep` | `AddRep(rep, amount)` | Updates `metadata.rep` |
| `RemoveRep` | `RemoveRep(rep, amount)` | Updates `metadata.rep` without going below zero |
| `GetRep` | `GetRep(rep)` | Current reputation value, default `0` |
| `AddMoney` | `AddMoney(moneyType, amount, reason)` | Boolean success |
| `RemoveMoney` | `RemoveMoney(moneyType, amount, reason)` | Boolean success |
| `SetMoney` | `SetMoney(moneyType, amount, reason)` | Boolean success |
| `GetMoney` | `GetMoney(moneyType)` | Current balance for the money type |
| `Save` | `Save()` | Persists the current player |
| `Logout` | `Logout()` | Runs the core logout path |
| `AddMethod` | `AddMethod(methodName, handler)` | Adds a bound method to this player interface |
| `AddField` | `AddField(fieldName, data)` | Adds a field to this player interface |

This table describes the core's current bound surface, not inventory methods from older QBCore
versions or third-party forks.

## Client-Side Data Synchronization

### Listening for Updates

In this revision, `QBCore:Client:OnPlayerUpdated(key, value)` carries field updates and `all`
snapshots. Core forwards `OnJobUpdate` and `OnGangUpdate` for those fields. The client
`QBCore:Player:SetPlayerData` compatibility event is forwarded on a full snapshot, not every update.

```lua
-- client.lua: this local cache is presentation state only.
local QBCore = exports['qb-core']:GetCoreObject()
local playerData = {}

local function Bootstrap()
    local data = QBCore.Functions.GetPlayerData()
    playerData = data and data.citizenid and data or {}
end

RegisterNetEvent('QBCore:Client:OnPlayerLoaded', Bootstrap)
RegisterNetEvent('QBCore:Client:OnPlayerUnload', function()
    playerData = {}
end)
RegisterNetEvent('QBCore:Client:OnPlayerUpdated', function(key, value)
    if key == 'all' then
        playerData = type(value) == 'table' and value or {}
    elseif type(key) == 'string' and playerData.citizenid then
        playerData[key] = value
    end
end)

AddEventHandler('onClientResourceStart', function(resource)
    if resource == GetCurrentResourceName() and LocalPlayer.state.isLoggedIn then
        Bootstrap()
    end
end)
```

Do not rely on registration order between resources when reading another resource's cache inside
a handler. Use the supplied event payload. A cache must not authorize server-side actions.

### Triggering Updates

Use the server-side player methods. `SetJob`, `SetMetaData` and `SetPlayerData` already call the
core update path. Do not follow them with an extra hand-built client event using a legacy payload.

## Advanced Usage

### Custom Player Functions

Prefer a helper with an explicit Player argument over mutating core's method table:

```lua
local function CanAfford(Player, amount)
    if not Player or type(amount) ~= 'number' then return false end
    if amount ~= amount or amount <= 0 or amount == math.huge then return false end
    return (Player.Functions.GetMoney('bank') or 0) >= amount
end
```

`Player.Functions` contains bound wrappers: call them with a dot, such as
`Player.Functions.GetMoney('bank')`. Do not define `function(self, amount)` and then call it with
only `amount`; the first argument would be assigned to `self` instead.

### Batch Operations

Multiple `SetMoney`/`SetMetaData` calls are multiple updates, not one atomic transaction. A feature
spanning database writes, money and inventory needs its own consistency/recovery design.

## Data Validation

### Server-Side Validation

Validate identity, permission, job/duty, input types/ranges, server-known state and proximity where
relevant. A loaded Player is a prerequisite, not proof of authorization. See
[safe server events](/docs/security/safe-server-events).

## Best Practices

### 1. Always Check Player Existence

Look up a Player at the operation boundary, not once at resource startup for later reuse.

### 2. Use Proper Money Management

Use core money methods, fixed server-owned prices, and meaningful reason strings.

### 3. Validate Data Types

Reject non-finite numbers, invalid ranges and malformed nested objects before accessing fields.

### 4. Use Metadata for Custom Data

Use resource-owned keys, explicit defaults and a migration plan for changed field types.

## Related Documentation

- [Core object](/docs/core/core-object)
- [Server functions](/docs/api/server-functions)
- [Client functions](/docs/api/client-functions)
- [Set player job](/docs/guides/set-job)
- [Database structure](/docs/database/core-schema)

## Common Patterns

### Resource Initialization with Player Check

```lua
-- server.lua: the local hook receives a Player object at this revision.
AddEventHandler('QBCore:Server:PlayerLoaded', function(Player)
    if not Player or not Player.PlayerData then return end
    print(('Initializing character %s'):format(Player.PlayerData.citizenid))
end)
```

For resource restarts, bootstrap `GetQBPlayers()` too; make initialization repeatable and never
use it to grant unconditional rewards. Register hooks once, not inside every login handler.

### Player Disconnect Cleanup

Use `QBCore:Server:OnPlayerUnload(src)` for character logout and `playerDropped` for connection
cleanup. Clear state before a reused connection ID can inherit it.

## Sources

- [Pinned Player class and update methods](https://github.com/qbcore-fivem/qb-core/blob/9b3cddcce93e5e12cbcf6b47b866b687d32ac7bf/server/player.lua)
- [Pinned client synchronization](https://github.com/qbcore-fivem/qb-core/blob/9b3cddcce93e5e12cbcf6b47b866b687d32ac7bf/client/events.lua)
- [Pinned disconnect lifecycle](https://github.com/qbcore-fivem/qb-core/blob/9b3cddcce93e5e12cbcf6b47b866b687d32ac7bf/server/events.lua)
