简体   繁体   中英

laravel authorization ability check too few arguments

blade:

@can('see_similar', $similar, $in_pair)
...
@endcan

class AuthServiceProvider extends ServiceProvider:

public function boot()
{
    $this->registerPolicies();
    Gate::define('see_similar', function ($user, $similar, $in_pair) {
        return count($similar) > 0 && (isset($in_pair)) && $in_pair !== 'in_pair';
    });
}

It gives me this error:

Too few arguments to function App\Providers\AuthServiceProvider::App\Providers{closure}(), 2 passed in /var/www/html/vendor/laravel/framework/src/Illuminate/Auth/Access/Gate.php on line 452 and exactly 3 expected (View: /var/www/html/resources/views/daters.blade.php)

Though it works if I pass just one argument "...function($user, $similar)" for example. I tried to pass an array of args, didn't work.

Please explain to me how can I pass several arguments.

From the doc:

Gates always receive a user instance as their first argument, and may optionally receive additional arguments such as a relevant Eloquent model

Your problem is that you are passing 3 parameters to the closure function, you need to remove one.

public function boot()
{
    $this->registerPolicies();
    // Here you MUST pass at most 2 parameters
    Gate::define('see_similar', function ($user, $ELOQUENT_MODEL) {
        return $what_you_want; // A boolean value
    });
}

Barmaxon, your boot() is ok!

You need to check web.php if your route has ->middleware('can:see_similar')

I have removed it and then could pass many variables:

public function abc()
    {
        $x=1;$y=2;
        $this->authorize('see_similar',[$x,$y]);
        return view('abc');
    }

Or you can leave ->middleware('can:see_similar') in routes and edit your boot()

public function boot()
{
    $this->registerPolicies();
    Gate::define('see_similar', function ($user, $similar=null, $in_pair=null)....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM