Posts Learn Components Snippets Categories Tags About
/

How to Alias Column Name in Laravel Select

Learn how to alias the column name of a table inside the eloquent select statement

Created on Aug 06, 2021

37 views

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();

Snippets by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.

Load comments for How to Alias Column Name in Laravel Select