php - (concept Confusion) AppUser::role must return a relationship instance (eloquent relation work but query builder not working)
Get the solution ↓↓↓I am creating AdminAuthenticated middleware
public function handle($request, Closure $next)
{
if (Auth::user()->role->name == 'customer') {
return redirect('/home')->with('message', 'You are not allowed to access');
}
return $next($request);
}
My Question is when i use eloquent relation it will work fine but when i use query builder its throw error
This code works
public function role(){
//this code work
return $this->belongsTo('App\Role');
}
This code throw error why this happen and how to use below code(query builder)
public function role(){
//this code not work throw exception
return DB::table('users')
->join('roles', 'roles.id', '=', 'users.role_id')
->select('roles.*')
->where('users.id','=',$this->id);
}
Answer
Solution:
because the relation is many to many ...there is a pivot table between users and roles tables..
in 'join' you can not ignore pivot tables....
if you are using Spatie
then your 'join' should be:
public function role(){
return DB::table('users')
->join('model_has_roles',function($join){
$join->on('users.id', '=', 'model_has_roles.model_id')
where('model_has_roles.model_type','=',User::class);}) )
->join('roles','roles.id','=','model_has_roles.role_id')
->select('roles.*')
->where('users.id','=',$this->id);
}
note: i recommend renaming your method to 'roles' instead of 'role'
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: call to a member function getclientoriginalname() on null
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.