Laravel:在构造方法中访问模型属性 [英] Laravel: Accessing model attributes in the constructor method

查看:258
本文介绍了Laravel:在构造方法中访问模型属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在laravel雄辩地使用__construct并获取属性.我很累:

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

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

我的代码返回null.但是在抽象类上,Model填充了所有属性:

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?

推荐答案

我在本地通过更新构造函数来对此进行了测试:

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.

也许事件或观察员可以为您提供所需的帮助: https://laravel.com/docs/5.8/eloquent#events
https://laravel.com/docs/5.8/eloquent#observers

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

这篇关于Laravel:在构造方法中访问模型属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆