timmyc
timmyc

Reputation: 522

Laravel 5 - Error accessing many-to-many data

In a Laravel 5 app, I have a "User" model and a "Permission" model, both with corresponding tables, that have a many-to-many relationship. There is a pivot table as well: "permission_user".

The User model contains the following method:

public function permissions()
{
    return $this->belongsToMany('App\Permission');
}

And the Permission model contains the following method:

public function users()
{
    return $this->belongsToMany('App\User');
}

I have been accessing user permissions in custom middleware with the following code, and it's been working splendidly until today.

$permissions = \Auth::user()->permissions()->get();

All of a sudden, this is breaking. I get the following error:

ErrorException in BelongsToMany.php line 177: Argument 1 passed to Illuminate\Database\Eloquent\Relations\BelongsToMany::hydratePivotRelation() must be of the type array, object given, called in /Server/sites/app/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php on line 158 and defined

Really not sure what's going on here. In an attempt to follow the docs more closely, I also tried this:

foreach (\Auth::user()->permissions as $permission)
{
    // do something with $permission
}

But I get the same thing (the stack trace shows that the lines shown here are the last ones executed before heading into the Laravel source). I did update Laravel with Composer around the time this happened, but thought it unlikely that something in Laravel source has caused the problem. Can anyone see what I might be doing wrong here, and how I can fix it?

Upvotes: 0

Views: 719

Answers (1)

John
John

Reputation: 295

Sit tight, I believe this might actually just a current bug with Laravel 5 (which is still technically in alpha, so breaking changes are to be expected).

Taylor Otwell (the creator of Laravel) tweeted this earlier:

https://twitter.com/taylorotwell/status/553262692426059776

However, it looks like several parts of Laravel 5 core still need to be updated to be compatible with this change.

If you need your app to work right now, just change this in your composer.json file:

"laravel/framework": "~5.0",

to this:

"laravel/framework": "dev-master#9b108d85ce19300dfdd479fa4e05d9ea6e4e3abc",

And then run a composer update. This will pull in yesterdays version of Laravel 5, which was working.

Don't forget to change it back though once this is fixed!

Upvotes: 1

Related Questions