Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation

StackOverflow https://stackoverflow.com/questions/23546110

  •  18-07-2023
  •  | 
  •  

Question

Trying to get a list of users associated with an event. Here are my eloquent models:

User.php:

public function fbevents()
{
    $this->belongsToMany('Fbevent', 'fbevent_user');
}

Fbevent.php:

public function users()
{
    $this->belongsToMany('User', 'fbevent_user);
}

I get this error when I try to find the list:

$event = Fbevent::find(10);
var_dump($event->users->lists('userId'));

I've set up a pivot table in the db with the following migration:

$table->increments('id');
$table->integer('fbevent_id')->unsigned()->index();
$table->foreign('fbevent_id')->references('id')->on('fbevents')->onDelete('cascade');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();

And added an entry in the fbevent_user table with fbevent_id = 10 and user_id = 1.

Was it helpful?

Solution

You need to return a result from your relations

public function fbevents()
{
    return $this->belongsToMany('Fbevent', 'fbevent_user');
}
public function users()
{
    return $this->belongsToMany('User', 'fbevent_user');
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top