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

1 answer

  • answered 2021-02-24 11:02 BABAK ASHRAFI

    As is return a collection, you may use pluck()

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