skip to Main Content

I have a isAdmin() which return true if exist record. I have 2 where condition. I first I check if role is Admin and second where check if id is user logged id. And my problem is how I check to second where id currently logged id user.
model

2

Answers


  1. Laravel has an Auth facade that can help retrieve user details. So basically add it to the top of your file then call it as such:

    use Auth;
    public $userId = Auth::user()->id;
    
    protected $fillable = [
        'login',
        'password',
        'email',
        'role',
    ];
    
    protected $hidden = [
        'password',
    ];
    
    public function isAdmin()
    {
        return User::where('role', 'Admin')->where('id', $userId)->exists();
    }
    

    Although it is much better to do this in your controller instead.

    Login or Signup to reply.
  2. To use anywhere like this:

    auth()->user()->isAdmin() // returns true or false
    

    You can update the isAdmin() function in your User model like this:

    public function isAdmin()
    {
        return $this->role == 'Admin';
    }
    

    This will give you whether the logged in user has the Admin role.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search