nowox
nowox

Reputation: 29178

How to get the current attributes of an Eloquent model?

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

Answers (4)

ManojKiran
ManojKiran

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

Mamadou Hady Barry
Mamadou Hady Barry

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

Lijesh Shakya
Lijesh Shakya

Reputation: 2540

To get the attributes without its values

  1. For model instance:

    array_keys($model->getAttributes())

  2. For model's table name:

    Schema::getColumnListing('tasks');

Upvotes: 1

tohasanali
tohasanali

Reputation: 934

Use array_keys($model->toArray()) to find the arrays. It will show you arrays of keys.

Upvotes: 1

Related Questions