This is the documentation for
v3 but the latest version is
v5
.
You can switch versions in the menu on the left/at the top.
Check your current version with the following command:
composer show spatie/laravel-query-builder
When serializing a model to JSON, Laravel can add custom attributes using the append
method or appends
property on the model. The query builder also supports this using the allowedAppends
method and append
query parameter.
##Basic usage
Consider the following custom attribute accessor. It won't be included in the model's JSON by default:
class User extends Model
{
public function getFullnameAttribute()
{
return "{$this->firstname} {$this->lastname}";
}
}
Using allowedAppends
we can optionally include the given above append.
// GET /users?append=fullname
$users = QueryBuilder::for(User::class)
->allowedAppends(['fullname'])
->get();
// Will call `$user->append('fullname')` on the query's results
Of course you can pass a list of attributes in the request to be appended:
// GET /users?append=fullname,ranking