1
votes

I want to add additional data to $user collection so can get the profile fields in the view

I have tried using $user['profileFields'] = $this->getProfileFields() and pass $user to the view using compatct or with and this is working fine.

DD

enter image description here

However, I have found some reference over the net saying I can extend using map but when I tried it is giving the following error

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

So here is what I am trying to understand

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'));
}
2

2 Answers

1
votes

collection methods are works on the collection, here you're getting the object of user.

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

If the profileFields is in another table and having a foreign key with model ProfileField, then try to add a one to one relation to the User model.

Inside the User model, add a function

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

This will give you the profileFields in every user when calling using eloquent.