I'm making a blog with laravel. When I look into user authentication, I have a few issues here. I have 2 tables, one is users: id, name, ... the other is role: user_id, privilege .. I need to check whether a user is admin or not, I will need a function like isAdmin()
or a $isAdmin
attribute. This is my function placed in the app/providers/AuthServiceProvider.php:
private static $isAdmin;
public static function isAdmin() {
if (isset(self::$isAdmin)) {
return self::$isAdmin;
}
$user_privilege = DB::table('role')
->select('privilege')
->where([
['privilege', '=', 'admin'],
['user_id', '=', Auth::user()->id],
])
->get()
->first();
self::$isAdmin = isset($user_privilege->privilege);
return self::$isAdmin;
}
This code works fine, but this will require two queries to the database to check the user's admin rights. So I wanted to find a way to inject a query into Auth :: user () so that only one query would retrieve all the stuff I wanted. I'm a beginner with laravel. Can you help me?