Get Laravel Models with All Attributes
$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!!
I have this snippet on my other project to load all model attributes and relation.
public function forModel($with)
{
$this->load($with);
$attributes = $this->toArray();
// Normalize Null Relation To Empty Model
foreach ($attributes as $key => $value) {
if (
is_null($value) &&
method_exists($this, Str::camel($key)) &&
$this->{Str::camel($key)}() instanceOf \Illuminate\Database\Eloquent\Relations\Relation
) {
$relation = $this->{Str::camel($key)}();
$model = $relation->getModel();
$attributesForRelation = $model->getAttributes();
foreach ($model->getFillable() as $column)
{
if (! array_key_exists($column, $attributesForRelation))
{
$attributesForRelation[$column] = null;
}
}
$attributes[$key] = $attributesForRelation;
} else {
$attributes[$key] = $value;
}
}
return $attributes;
}
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.
Update:
If you are trying to do this after instantiating like so:
$model = new Model;
then please differ to Thomas Kim's answer.
Otherwise:
You could use the toArray()
or getArributes()
method on the model instance, that would give back all the attributes including nulls. Then you can use array_key_exists
to check.
Like so:
if (array_key_exists('foo', $model->getAttributes())) {
$model->foo = 'new value';
}