Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Laravel Models with All Attributes

Is there a way to retrieve a model in Laravel with all the attributes, even if they're null? It seems to only return a model with the attributes that aren't null.

The reason for this is that I have a function that will update the model attributes from an array, if the attributes exists in the model. I use the property_exists() function to check the model if it has a particular attribute before setting it. The array key and model attribute are expected to match, so that's how it works.

It works fine if the model already has the attributes set, because the attribute exists and takes the value from the array. But nothing will get updated or set if the attribute was previously null, because it fails the property_exists() check.

What's ultimately happening is that I have a single array of attributes, and then perhaps two models. And I run my setter function, passing in the attributes array, and each of the objects in separate calls. If the model has a matching property, it gets updated.

like image 283
kenshin9 Avatar asked Nov 04 '15 01:11

kenshin9


2 Answers

Here are two ways to do this. One method is to define default attribute values in your model.

protected $attributes = ['column1' => null, 'column2' => 2]; 

Then, you can use the getAttributes() method to get the model's attributes.

If you don't want to set default attributes though, I wrote up a quick method that should work.

public function getAllAttributes() {     $columns = $this->getFillable();     // Another option is to get all columns for the table like so:     // $columns = \Schema::getColumnListing($this->table);     // but it's safer to just get the fillable fields      $attributes = $this->getAttributes();      foreach ($columns as $column)     {         if (!array_key_exists($column, $attributes))         {             $attributes[$column] = null;         }     }     return $attributes; } 

Basically, if the attribute has not been set, this will append a null value to that attribute and return it to you as an array.

like image 137
Thomas Kim Avatar answered Oct 09 '22 00:10

Thomas Kim


$model->getAttributes(); 

Above will return an array of raw attributes (as stored in the database table)

$model->toArray()  

Above will return all the model's raw, mutated(if used), and appended attributes

Hope it will helpful!!

like image 34
Mahesh Yadav Avatar answered Oct 09 '22 02:10

Mahesh Yadav