laravel mutator:访问其他属性

时间:2021-05-07 18:16:25

标签: laravel

我安装了一个普通的 Laravel 8,并添加了一个 mutator 来访问该模型的其他属性。

例如:想将姓名设置为姓名+电子邮件地址。

我试过了:

    public function setNameAttribute($value) {
        $this->attributes['name'] = $value .' - '. $this->attributes['email'];
    }

并测试:

>>> User::factory()->make()
[!] Aliasing 'User' to 'App\Models\User' for this Tinker session.
<warning>PHP Warning:  Undefined array key "email" in .../app/Models/User.php on line 45</warning>
=> App\Models\User {#3399
     name: "Mr. Johathan Becker - ",
     email: "dsteuber@example.com",
     email_verified_at: "2021-05-07 18:10:35",
     #password: "$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi",
     #remember_token: "bihwTV6T4E",
   }

所以:$this->attributes 不包含“电子邮件”。

我可以访问该模型的其他属性吗?

我可以想象,即使有可能,mutator 也不能保证相关属性已经设置。

更新:matiaslauriti 的评论解决了上面的简化示例。谢谢!设置属性的顺序很重要。之后我可以同时使用 $this->attributes['name']$this->name

我更复杂的用例是:我想为用户 ($user->posts()->create([...])) 创建一个帖子,并且在设置帖子属性时我想访问“用户”。因此,在这种情况下,用户已经设置,我们可以假设“用户”可用。但是在 Post mutator $this->user 中给出了 null。建议?

1 个答案:

答案 0 :(得分:0)

你可以试试 $this->email 而不是 $this->attributes['email']

相关问题