I have a simple Userpermission System consisting of 3 tables: users, permissions and the pivot table permission_user.
This is the User model:
JavaScript
x
<?php
namespace App;
use IlluminateContractsAuthMustVerifyEmail;
use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateNotificationsNotifiable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function permissions()
{
return $this->belongsToMany('AppPermission');
}
}
and here is the Permission Model:
JavaScript
<?php
namespace App;
use IlluminateDatabaseEloquentModel;
class Permission extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'description', 'level', 'parentpermission',
];
public function users()
{
return $this->belongsToMany('AppUser');
}
}
Now when I try to get all the permissions of the currently logged in user with this:
JavaScript
$user_permissions = Auth::user()->permissions()->get();
it works without problems.
But when I try to get another Users Permissions like this:
JavaScript
$user_permissions = User::where('id', '=', $userid)->permissions()->get();
I get the following error:
JavaScript
Method IlluminateDatabaseEloquentCollection::permissions does not exist.
How do I proceed?
Advertisement
Answer
I think you’re missing first()
here, since you can’t get relations of a query builder object. Try this :
JavaScript
$user_permissions = User::where('id', '=', $userid)->first()->permissions()->get();
This first()
will actually return User
object, and then you can load its relations.