0

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.

1
  • Are you using API resources or do you return plain arrays or models? With API resources, renaming is straight forward. Commented Apr 5, 2019 at 4:16

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

question. If you do this, can you modify fillable using the alias? I'm looking at a use case where I could use a single 'abstract' model type for user details for buyer vs. seller vs. shipping address. so id could be aliased to buyer_user_id (used for both buyer and shipment) or seller_user_id depending on the incoming rest data.
1

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,
        ]);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.