Home > Back-end >  How to check id logged in where condition?
How to check id logged in where condition?

Time:01-16

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

CodePudding user response:

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.

CodePudding user response:

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.

  • Related