Laravel 8 Gate issue iam trying to check condition with different model but there are error show

832 views Asked by At

In my laravel 8 iam define gate but there some problem my gate is accept only one model name is that Admin when i try to check another model name there are error show

here is my authserviceprovider

<?php

namespace App\Providers;

use App\Models\Admin\Role; use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; use Illuminate\Support\Facades\Gate;

class AuthServiceProvider extends ServiceProvider { /** * The policy mappings for the application. * * @var array */ protected $policies = [ // 'App\Models\Model' => 'App\Policies\ModelPolicy', ];

/**
 * Register any authentication / authorization services.
 *
 * @return void
 */
public function boot()
{
    $this->registerPolicies();
    
    Gate::define('isAdmin', function(Role $role) {

        if ($role->role === 'Admin') {
            return true;
        } else {
            return false;
        }
    });
}

}

here is controller

 public function index(Role $role)
{
    if (!Gate::allows('isAdmin', $role)) 
    {
        abort(403);
    }

    $users = Admin::with('roles')->get();
    return view('Admin.user.index', compact('users'));
}

error message

TypeError

App\Providers\AuthServiceProvider::App\Providers{closure}(): Argument #1 ($role) must be of type App\Models\Admin\Role, App\Models\Admin given, called in D:\xampp\htdocs\education\vendor\laravel\framework\src\Illuminate\Auth\Access\Gate.php on line 477 http://127.0.0.1:8000/admin/users

1

There are 1 answers

0
Kamlesh Paul On

Gate are mostly used to authored login user. if you need to authorise in any model specific then use policy

so in gate we get login user instance as call back automatically

so in your case code will be like this

/**
 * Register any authentication / authorization services.
 *
 * @return void
 */
public function boot()
{
    $this->registerPolicies();

    Gate::define('isAdmin', function($user) {
       return $user->role->name === 'Admin';
    });
}

then in controller

public function index(Role $role)
{
    abort_if(!Gate::allows('isAdmin'));

    $users = Admin::with('roles')->get();
    return view('Admin.user.index', compact('users'));
}