N
N
Nikolino2018-09-01 19:37:46
Laravel
Nikolino, 2018-09-01 19:37:46

How to get user name from belongsTo collection?

In the controller

public function getUserPhotos($id)
    {
        $photos = Photo::with('user')->where('user_id', $id)->get();
        $user = User::find($id);
        return view('user.userphotos', [
            'photos' => $photos,
            'user' => $user
        ]);
    }

If I pass foreach through $photos, then I can get the username, but if I just want to display $photos->user->name, then it does not.
Because of this, you have to do this $user = User::find($id); and makes another request to the database.
Whether it is possible to make so that not to climb once again in basis receiving username?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Kirill Nesmeyanov, 2018-09-01
@SerafimArts

Well, like this:

$user = User::with('photos')->where('id', $id)->first();

return \view('....', ['photos' => $user->photos, 'user' => $user]);

D
Denis Bukreev, 2018-09-01
@denisbookreev

$photos is an array, it does not have a name property, only the elements of this array have this property.
So the only way is with a separate receipt of the user, but you can remove the user selection for the photo.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question