Home » Php » Laravel 5.1 @can, how use OR clause

Laravel 5.1 @can, how use OR clause

Posted by: admin October 29, 2017 Leave a comment

Questions:

I did not find how to use a clause (OR, AND) in view with @can, for checking multiple abilities …

I tried:

@can(['permission1', 'permission2']) 
@can('permission1' or 'permission2')
@can('permission1' || 'permission2')

But dont work ;(

Answers:

You can use the Gate facade:

@if(Gate::check('permission1') || Gate::check('permission2'))

@endif

Questions:
Answers:

I’ve added this directive in my Laravel 5.4 app that allows me to use a new @canany('write|delete') directive in my blade views.

// [email protected]()

Blade::directive('canany', function ($arguments) {
    list($permissions, $guard) = explode(',', $arguments.',');

    $permissions = explode('|', str_replace('\'', '', $permissions));

    $expression = "<?php if(auth({$guard})->check() && ( false";
    foreach ($permissions as $permission) {
        $expression .= " || auth({$guard})->user()->can('{$permission}')";
    }

    return $expression . ")): ?>";
});

Blade::directive('endcanany', function () {
    return '<?php endif; ?>';
});

Example in blade view:

@canany('write|create')
    ...
@endcanany

Here’s the doc for extending Blade on 5.4

Questions:
Answers:

You can call @can multiple times.

@if( @can(‘permission1’) || @can(‘permission2’) )

@if( Gate::check('permission1') || Gate::check('permission2') )