'Get current logged in user's user role from a laravel controller

In my laravel application I have two user tyoes, admins and general users.

I have implemented function for users to download their certificates.

For that I got following function inside my controller

public function index(string $locale, CertificateUser $certificateUser)
    {
        
        $this->authorize('downloadCertificate', [Institute::class, $certificateUser, $institute]);

        try {
            return Storage::download($certificateUser->certificate_url);
        } catch (FileNotFoundException $exception) {
            return redirect()->back()->withErrors(__('Certificate could not be found.'));
        }
    }

now I want to execute this

$this->authorize('downloadCertificate', [Institute::class, $certificateUser, $institute]);

only if the logged in user's user role is an admin...

How can I get the current logged in User's user role from here?



Solution 1:[1]

>  $user_role = Auth::user()->role;
>  if($user_role  == 'admin'){
>  // You code Here
> $this->authorize('downloadCertificate', [Institute::class, $certificateUser, $institute]); } What's the issue ? 

.Also Share you User Model Here

Other Ways ....

 if($user->hasRole->name('Admin'))
 $user_roles = Auth::user()->roles()->get();

Now You can loop through $user_roles ..

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1