Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping field name in model using laravel

Is there a way to map field names to a database to a different attribute name in the model? For example, if the database has a field name of customer_id but I wanted to use eloquent in this way Customer::get(['id']) I've tried using the getAttribute method but that is called after eloquent has attempted to get the value.

like image 213
Casey Avatar asked Apr 30 '15 23:04

Casey


Video Answer


1 Answers

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):

// Customer model
protected $maps =[
  'id' => 'customer_id',
  'name' => 'customer_name',
  ...
];

// then you can do this:
$customer = Customer::where('name', 'whatever')->first();
// calls WHERE customer_name = ? sql

$customer->id; // customer_id column
$customer->name; // customer_name column
$customer->name = 'different name'; // set mutator works as well

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

like image 173
Jarek Tkaczyk Avatar answered Sep 27 '22 22:09

Jarek Tkaczyk