Search code examples
laravellaravel-collection

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


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

Solution

  • 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'));