Martin
Martin

Reputation: 33

Laravel alias column name in Eloquent model

How can I alias a column name in a model? I would like to show idUser instead of id in API responses. So far I've tried the following.

protected $maps = [
    'id' => 'idUser',
];

protected $visible = [
    'idUser'
];

protected $appends = [
    'idUser'
];

This gives me an error:

'Call to undefined method App\User::getIdUserAttribute()'

Also, I would like to alias created_at and updated_at to createdAt and updatedAt.

Upvotes: 0

Views: 6466

Answers (2)

vozaldi
vozaldi

Reputation: 1077

As @Namoshek's comment, you should be able to return a custom aliases for each column by renaming it.

First, look for which route you want to edit in folder routes/api.php. You can either use callback function or a Controller to manage the response.

// routes/api.php
Route::middleware('auth:api')->get('auth/retrieve-user', function(Request $request) {
    $user = Auth::user();

    return response()
        ->json([
            'userId' => $user->id,
            'createdAt' => $user->created_at,
            'updatedAt' => $user->updated_at,
        ]);
});

Upvotes: 1

Ali Faris
Ali Faris

Reputation: 18620

you can define accessor method in your model like this :

public function getUserIdAttribute($)
{
    return $this->id;
}

and then you have to add the attribute name in the $appends array

protected $appends = ['user_id'];

for more details checkout the docs

https://laravel.com/docs/5.8/eloquent-mutators

Upvotes: 2

Related Questions