1
votes

How to use __construct on laravel eloquent and get attributes. I tired:

public function __construct() {
    parent::__construct();
    dd($this->attributes);
}

My code return null. But on abstract class Model filled all attributes:

public function __construct(array $attributes = [])
{
    $this->bootIfNotBooted();

    $this->initializeTraits();

    $this->syncOriginal();

    $this->fill($attributes);
}

It's possible get access to model attributes in the constructor method?

2

2 Answers

0
votes

Try with accessors.

https://laravel.com/docs/5.8/eloquent-mutators#accessors-and-mutators

Define it like:

public function getFirstNameAttribute($value)
{
     return ucfirst($value);
}

And use $this->first_namesomething like this.

0
votes

I tested this locally by updating the constructor like this:

public function __construct(array $attributes = []) {
    parent::__construct($attributes);
    dd($this->getAttributes());
}

However, I've discovered that when fetching the object from the database, its attributes are not filled in the constructor, and therefore it's not possible to access them there.

What you can do is access the attributes after the object has been initialized:

$post = Post::find(1);
dump($post->getAttributes());

Not sure if that helps, but it is what it is.

Maybe Events or Observers can help you with what you need: https://laravel.com/docs/5.8/eloquent#events
https://laravel.com/docs/5.8/eloquent#observers