Laravel: Accessing model attributes in the constructor method

社会主义新天地 提交于 2019-12-11 06:47:35

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/56376177/laravel-accessing-model-attributes-in-the-constructor-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!