Reputation: 29178
I would like to get the keys of a model, not the columns in the database.
Here an example of what I would like to achieve:
>>> $model = Model::first();
=> [
"foo" => 3,
"bar" => 4
]
>>> $model->baz = 5;
>>> $model->keys() // What I would like to do...
=> ["foo", "bar", "baz"]
Unfortunately get_object_vars
does not work here.
Upvotes: 1
Views: 834
Reputation: 6351
Laravel Has a buit in out of the Method to do that
this Method Wsa introduced in laravel 5.4
So only app with 5.4 or with higher verision will only work
//gets the first model from the table
$model = Model::first();
//to get the original data With value
$originalAndData = $model->getOriginal();
//to get only the filed names
$originalKey = array_keys($model->getOriginal());
Upvotes: 1
Reputation: 629
<?php
Hi nowox,
//in your Model create a method getKeysAtribute like
...
public function getKeysAttribute() {
return array_keys($this->attributes);
}
...
$model->keys() // ['key1', 'key2', ...];
Upvotes: 1
Reputation: 2540
To get the attributes without its values
For model instance:
array_keys($model->getAttributes())
For model's table name:
Schema::getColumnListing('tasks');
Upvotes: 1
Reputation: 934
Use array_keys($model->toArray())
to find the arrays. It will show you arrays of keys.
Upvotes: 1