Matt Pierce
Matt Pierce

Reputation: 805

Laravel Many To Many Method Issue

I have a many to many relationship between the models User & Notification.

User Model:

public function notifications()
{
    return $this->belongsToMany('Yeayurdev\Models\Notification', 'notifications_user', 'user_id', 'notification_id')
        ->withPivot('notifier');
}

Notification Model:

public function user()
{
    return $this->belongsToMany('Yeayurdev\Models\User', 'notifications_user', 'notification_id', 'user_id');
}

Pivot Table:

ID     USER_ID     NOTIFICATION_ID
1         2               1

In my view, I retrieve a list of all notifications for a user like so.

@foreach (Auth::user()->notifications as $notification)
   {{ $notification->user->username }}
@endforeach

The problem is that when I try to get the username of the user with that notifications, I get the error Undefined property: Illuminate\Database\Eloquent\Collection::$username. "Username" is the column on my users table which is just a string. I don't see where I'm going wrong because if I just do "$notificatin->user" it gives me the collection.

Thanks!

Upvotes: 0

Views: 40

Answers (1)

Tadas Paplauskas
Tadas Paplauskas

Reputation: 1903

As you said, the relationship is many-to-many, so $notification->user in your case is returning a collection of User models, NOT a single user. If you need only a first user then just do

{{ $notification->user()->first()->username }}

If you need to print out all users for every notification, then you will need a loop here to go through all users.

@foreach (Auth::user()->notifications as $notification)
    @foreach($notification->user as $notificationUser)
        {{ $notificationUser->username }}
    @endforeach
@endforeach

I would recommend renaming user() relationship to users() to avoid confusion in the future.

Upvotes: 6

Related Questions