BadMethodCallException 调用未定义的方法 App\User::map()

BadMethodCallException Call to undefined method App\User::map()

我想向 $user 集合添加额外的数据,以便可以在 view

中获取配置文件字段

我试过使用 $user['profileFields'] = $this->getProfileFields() 并使用 compatctwith$user 传递给视图,这工作正常。

DD

但是,我在网上找到了一些参考资料,说我可以使用 map 进行扩展,但是当我尝试时出现以下错误

BadMethodCallException
Call to undefined method App\User::map()

这就是我想了解的内容

Question:
Is the below code is wrong and won't work for what I am looking for and the first approach is the solution? Is there any recommended method to add additional data to the $user collection?

public function show(User $user)
{
    $user->map(function ($user){
       $user['profileFields'] = $this->getProfileFields();
       return $user;
    });

    return view('admin.user.show', compact('user'));
}

集合方法作用于集合,在这里你得到用户的对象。

$user->profileFields = $user->getProfileFields();
return view('admin.user.show', compact('user'));

如果 profileFields 在另一个 table 中并且有 foreign key 型号 ProfileField,则尝试将 one to one relation 添加到 User型号。

User 模型中,添加一个函数

public function profileFields()
{
    return $this->belongsTo('App\ProfileField', 'foreign_key','other_key');
}

当使用 eloquent.

调用时,这将为每个用户提供 profileFields