butaminas
butaminas

Reputation: 840

How to get specific column with custom column name on Laravel

Looking for a way to get specific columns from Laravel Eloquent with custom column names.

E.g. get example_name as name.

I am trying to replicate SQL Alias like SELECT column_name AS alias_name but without using custom attributes.

Here is and example query in Laravel:

Table::get(['column1', 'column2', 'column3'])->all()

And what I would like it to get would look something like this:

Table::get(['column1', 'column2 AS column4', 'column3'])->all()

Upvotes: 0

Views: 3722

Answers (1)

Jignesh Joisar
Jignesh Joisar

Reputation: 15085

for example in user model email as emailAddress u want to get then in your user model do like that

protected $appends = ['emailAddress']; //add custom column here..

public function getEmailAddressAttribute()
{
     return $this->email;
}

or u can use by query like that

User::select('id','name','email as emailAddress')->get();

Table::select('column1', 'column2 AS column4', 'column3')->get()

for more detail read https://laravel.com/docs/5.8/eloquent-mutators

Upvotes: 2

Related Questions