Home / Snippets / How to Alias Column Name in Laravel Select
How to Alias Column Name in Laravel Select cover

How to Alias Column Name in Laravel Select

3.1K

2 years ago

0 comments

When querying an eloquent model, you can alias / change the name of the selected column before returning it to the front-end. To do so you can make use of the "as" keyword within the "select" method.
$user = User::select(['id', 'name as nickname'])->first();

The query above will get the first user and the only column that will be retrieved is the "nickname".

If you are joining a table then make sure to use the "." dot syntax to specify which of the table column you are referring to.
Post::join('comments', 'posts.id', '=', 'comments.id')
    ->select('comments.title as subject')
    ->get();
notion avatar

Ahabz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this