0

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()
Jignesh Joisar
  • 13,720
  • 5
  • 57
  • 57
butaminas
  • 672
  • 7
  • 23
  • 1
    Possible duplicate of [Laravel 4 Eloquent Column Alias](https://stackoverflow.com/questions/17174837/laravel-4-eloquent-column-alias) – Amarnasan Jun 14 '19 at 12:51

1 Answers1

2

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

Jignesh Joisar
  • 13,720
  • 5
  • 57
  • 57