Home > OS >  Display relationship of relationship in response
Display relationship of relationship in response

Time:08-20

My stack is - Laravel, React, Vite. I have a relationship:

$messages = $user->profile->messages

and it works correctly, but messages have relationship with user. Propably it sound difficult but it's simple. Profile contains more details about user and profile has relationsin hasMany for Messages. It's simple. But I need to display messages with username (this is in Username model). How I said Messages have an relationship with User model but it's not in my response.

public function user() {
    return $this->belongsTo(User::class);
}

If I want to display only data from model with relationship I could use with, for example:

Book::with('author')->get()

But in this case it didn't work. For example

$user->profile->messages->with('user')

It display me the error

Method Illuminate\Database\Eloquent\Collection::with does not exist.

My question is - how could I add relationship (to user) to this query so that I can see that relationship in the response?

$user->profile->messages

CodePudding user response:

not sure what query you are using, but you can write something like this if you wish which should work assuming that the messages and user relationships are correctly defined

$user = User::with(['profile',
                    'profile.messages',
                    'profile.messages.user:id,username'])
              ->where(//some condition)->get()
  • Related