logeeks
logeeks

Reputation: 4979

Property does not exist in collection while using belongsToMany in laravel eloquent

I am using Laravel 8.X and eloquent to develop a web app.

I have a pivot table 'portal_event_users'

enter image description here

I am trying to add a belongsToMany relationship to the portal_users in the model of portal_event_users table.

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class EventUser extends Model
{
    use HasFactory;
    protected $table = 'portal_event_users';
    
      public function users()
    {
        return $this->belongsToMany(User::class);
    }
    
    public function events()
    {
        return $this->belongsToMany(Event::class);
    }
}

I have the following statements in the controller

$eventusersobj = \App\Models\EventUser::select('*')
                                    ->where('event_id', '=', $event_id)
                                    ->get();
                    
                    $response =  $eventusersobj->users->keyBy('id');

It is returning the following error

Property [users] does not exist on this collection instance.

Can someone please advice on how can i change this error?

Thanks in advance

Upvotes: 1

Views: 277

Answers (1)

SEYED BABAK ASHRAFI
SEYED BABAK ASHRAFI

Reputation: 4271

As it returns a collection, you can use pluck()

$eventusersobj->pluck('users')->each(function($user){
    $user->keyBy('id');
})

Upvotes: 1

Related Questions