0

I registered a Gate that should accept an array of integers. Its function is to return true if the user's role id is in that passed array. The code looks like this:

Gate::define('access', function ($user, $access_type) {
            Log::info('-----------------------------------');
            Log::info($access_type);
            Log::info(gettype($access_type));
            Log::info('-----------------------------------');

            return in_array($user->roleid,$access_type);
});

And in my template I placed that restriction like this:

@can('access',[2,4])
     ... html code here ...
@endcan

Now I get this error on the page:

enter image description here

I looked on the logs to check the value and type of the variable $access_type, and it looks like it only gets the value 2.. The 4 value is missing.

enter image description here

It looks like I have to add another variable on the anonymous function to get the value 4. Like this one:

Gate::define('access', function ($user, $access_type1, $access_type2){
  ... some code ...
})

When I added the new variable $access_type2 and looked at the logs, I was able to see the value 4. enter image description here

Now my problem is this:

  • I can't manually add the variables on the anonymous function because the values being passed differs in numbers. It can receive 1 value, 2 values, 3 values, and etc. How can receive the values in array format?
Lou
  • 83
  • 1
  • 7

1 Answers1

2

What about

Gate::define('access', function ($user, ...$access_types){
  ... some code ...
});

The ...$str is called a splat operator in PHP.

This feature allows you to capture a variable number of arguments to a function, combined with "normal" arguments passed in if you like.

Reference

Foued MOUSSI
  • 4,643
  • 3
  • 19
  • 39