NAME NO
NAME NO

Reputation: 75

How to change column name in laravel?

I am a beginner of laravel. Now, I would like to retrieve data from database using this code:

$data = Model::select('col1', 'col2', 'col3')->get();

and return $data to another view.

However, I would like to change the name of the columns. For example, changing col1 to column_1 before returning the array to the view. How can I change the column names? I am now using laravel 5.5. Thank you very much!

Upvotes: 2

Views: 5475

Answers (2)

Teoman Tıngır
Teoman Tıngır

Reputation: 2891

you can use selectRaw() method.

$data = Model::selectRaw('col1 as c1, col2 as c2, col3 as c3')->get();

Note that, all columns must be in the same string value.

Upvotes: 3

Mohammad_Hosseini
Mohammad_Hosseini

Reputation: 2599

You can use accessors to work with such attributes, but there's no way to query them this way with core eloquent. But fear not! Use this package https://github.com/jarektkaczyk/eloquence and you can easily achieve what you want (Mappable in particular):

// collection model 
protected $maps =['col1' => 'column_1','col2' => 'column_2',...];

// then you can do this:
$Col = Col::whereId($id)->first();// calls WHERE id = ? sql

$Col->col1; // column_1 column
$Col->col2; // column_2 column
$Col->col2 = 'different name'; // set mutator works as well

It's in heavy development and currently select is not yet supported, but it's a matter of a day or two, select support has been pushed already.

In your model do not forget

use Sofa\Eloquence\Eloquence; //base trait 
use Sofa\Eloquence\Mappable; // extension trait

and then inside your class

 use Eloquence, Mappable; 

This package is super! saves a lot of time.

Upvotes: 1

Related Questions