将数组传递给laravel

时间:2017-04-28 17:15:38

标签: php laravel authentication middleware

我在一个名为rolMiddleware的中间件中得到了这个句柄:

public function handle($request, Closure $next, $roles)
{
    //dd($request->user());
    foreach ($roles as $rol) {
        if ($request->user()->getTipoUsuario($request->user()->tipo_usuario_id)->getNombreTipoUsuario() == $rol) {
            return $next($request);
        }
    }
    abort(403, "¡No hay autorizacion!");
}

但$ roles是一个数组,这是我使用中间件的路线:

Route::get('/mid', ['middleware' => 'roles:super admin', function () {
    return "done";
}]);

并且给出的错误是:

ErrorException in RolMiddleware.php line 22:
Invalid argument supplied for foreach()

你可能不需要数组,因为我只在超级管理员中使用它,因为我只需要超级管理员,但是会有超级管理员和区域管理员的路由。

4 个答案:

答案 0 :(得分:8)

在laravel中,您可以使用逗号,将要传递给中间件的参数分开,如下所示:

Route::get('/mid', ['middleware' => 'roles:super,admin', function () {
//                                              ^ note this
    return "done";
}]);

请注意,这不会将参数作为数组发送,因此除非您将传递的参数用作ellipsis parameters,否则无法循环$roles,如下所示:

public function handle($request, Closure $next, ...$roles)

相反,您需要为每个角色使用一个参数:

public function handle($request, Closure $next, $role1, $role2) // .... and so on

答案 1 :(得分:0)

我并不完全明白你的功能是做什么的,但你可以尝试这样的事情:

public function handle($request, Closure $next, $roles)
{
    if(is_array($roles)){
        //dd($request->user());
        foreach ($roles as $rol) {
            if ($request->user()->getTipoUsuario($request->user()->tipo_usuario_id)->getNombreTipoUsuario() == $rol) {
                return $next($request);
            }
        }
    }else{
        if($request->user()->getTipoUsuario($request->user()->tipo_usuario_id)->getNombreTipoUsuario() == $roles)
            return $next($request);
    }
    abort(403, "¡No hay autorizacion!");
}

答案 2 :(得分:0)

路线:

2018-06-27 10:42:37.311029: W T:\src\github\tensorflow\tensorflow\core\framework\op_kernel.cc:1273] OP_REQUIRES failed at tensor_array_ops.cc:415 : Invalid argument: TensorArray decode_raw_image/TensorArray_1_0: Could not write to TensorArray index 2 because the value shape is [383463] which is incompatible with the TensorArray's inferred element shape: [292800] (consider setting infer_shape=False).
Traceback (most recent call last):
  File "C:\Users\shivam.agarwal\ml\ml\lib\site-packages\tensorflow\python\client\session.py", line 1327, in _do_call
    return fn(*args)
  File "C:\Users\shivam.agarwal\ml\ml\lib\site-packages\tensorflow\python\client\session.py", line 1312, in _run_fn
    options, feed_dict, fetch_list, target_list, run_metadata)
  File "C:\Users\shivam.agarwal\ml\ml\lib\site-packages\tensorflow\python\client\session.py", line 1420, in _call_tf_sessionrun
    status, run_metadata)
  File "C:\Users\shivam.agarwal\ml\ml\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 516, in __exit__
    c_api.TF_GetCode(self.status.status))
tensorflow.python.framework.errors_impl.InvalidArgumentError: TensorArray decode_raw_image/TensorArray_1_0: Could not write to TensorArray index 2 because the value shape is [383463] which is incompatible with the TensorArray's inferred element shape: [292800] (consider setting infer_shape=False).
     [[Node: decode_raw_image/while/TensorArrayWrite/TensorArrayWriteV3 = TensorArrayWriteV3[T=DT_UINT8, _class=["loc:@decode_raw_image/while/DecodeRaw"], _device="/job:localhost/replica:0/task:0/device:CPU:0"](decode_raw_image/while/TensorArrayWrite/TensorArrayWriteV3/Enter, decode_raw_image/while/Identity, decode_raw_image/while/DecodeRaw, decode_raw_image/while/Switch_1:1)]]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/shivam.agarwal/ml/ml/ML/apitoolkit/api/tf_record.py", line 499, in <module>
    print(label.eval())
  File "C:\Users\shivam.agarwal\ml\ml\lib\site-packages\tensorflow\python\framework\ops.py", line 656, in eval
    return _eval_using_default_session(self, feed_dict, self.graph, session)
  File "C:\Users\shivam.agarwal\ml\ml\lib\site-packages\tensorflow\python\framework\ops.py", line 5016, in _eval_using_default_session
    return session.run(tensors, feed_dict)
  File "C:\Users\shivam.agarwal\ml\ml\lib\site-packages\tensorflow\python\client\session.py", line 905, in run
    run_metadata_ptr)
  File "C:\Users\shivam.agarwal\ml\ml\lib\site-packages\tensorflow\python\client\session.py", line 1140, in _run
    feed_dict_tensor, options, run_metadata)
  File "C:\Users\shivam.agarwal\ml\ml\lib\site-packages\tensorflow\python\client\session.py", line 1321, in _do_run
    run_metadata)
  File "C:\Users\shivam.agarwal\ml\ml\lib\site-packages\tensorflow\python\client\session.py", line 1340, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.InvalidArgumentError: TensorArray decode_raw_image/TensorArray_1_0: Could not write to TensorArray index 2 because the value shape is [383463] which is incompatible with the TensorArray's inferred element shape: [292800] (consider setting infer_shape=False).
     [[Node: decode_raw_image/while/TensorArrayWrite/TensorArrayWriteV3 = TensorArrayWriteV3[T=DT_UINT8, _class=["loc:@decode_raw_image/while/DecodeRaw"], _device="/job:localhost/replica:0/task:0/device:CPU:0"](decode_raw_image/while/TensorArrayWrite/TensorArrayWriteV3/Enter, decode_raw_image/while/Identity, decode_raw_image/while/DecodeRaw, decode_raw_image/while/Switch_1:1)]]

Caused by op 'decode_raw_image/while/TensorArrayWrite/TensorArrayWriteV3', defined at:
  File "C:/Users/shivam.agarwal/ml/ml/ML/apitoolkit/api/tf_record.py", line 498, in <module>
    label = batch_example('CLASS.tfrecord', num_examples=4)
  File "C:/Users/shivam.agarwal/ml/ml/ML/apitoolkit/api/tf_record.py", line 397, in batch_example
    image_batch = decode_batch_example(reader(tfrecord), num_examples=num_examples)
  File "C:/Users/shivam.agarwal/ml/ml/ML/apitoolkit/api/tf_record.py", line 364, in decode_batch_example
    name='decode_raw_image')
  File "C:\Users\shivam.agarwal\ml\ml\lib\site-packages\tensorflow\python\ops\functional_ops.py", line 413, in map_fn
    swap_memory=swap_memory)
  File "C:\Users\shivam.agarwal\ml\ml\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 3202, in while_loop
    result = loop_context.BuildLoop(cond, body, loop_vars, shape_invariants)
  File "C:\Users\shivam.agarwal\ml\ml\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 2940, in BuildLoop
    pred, body, original_loop_vars, loop_vars, shape_invariants)
  File "C:\Users\shivam.agarwal\ml\ml\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 2877, in _BuildLoop
    body_result = body(*packed_vars_for_body)
  File "C:\Users\shivam.agarwal\ml\ml\lib\site-packages\tensorflow\python\ops\functional_ops.py", line 406, in compute
    tas = [ta.write(i, value) for (ta, value) in zip(tas, flat_fn_values)]
  File "C:\Users\shivam.agarwal\ml\ml\lib\site-packages\tensorflow\python\ops\functional_ops.py", line 406, in <listcomp>
    tas = [ta.write(i, value) for (ta, value) in zip(tas, flat_fn_values)]
  File "C:\Users\shivam.agarwal\ml\ml\lib\site-packages\tensorflow\python\util\tf_should_use.py", line 118, in wrapped
    return _add_should_use_warning(fn(*args, **kwargs))
  File "C:\Users\shivam.agarwal\ml\ml\lib\site-packages\tensorflow\python\ops\tensor_array_ops.py", line 879, in write
    return self._implementation.write(index, value, name=name)
  File "C:\Users\shivam.agarwal\ml\ml\lib\site-packages\tensorflow\python\util\tf_should_use.py", line 118, in wrapped
    return _add_should_use_warning(fn(*args, **kwargs))
  File "C:\Users\shivam.agarwal\ml\ml\lib\site-packages\tensorflow\python\ops\tensor_array_ops.py", line 278, in write
    name=name)
  File "C:\Users\shivam.agarwal\ml\ml\lib\site-packages\tensorflow\python\ops\gen_data_flow_ops.py", line 7853, in tensor_array_write_v3
    flow_in=flow_in, name=name)
  File "C:\Users\shivam.agarwal\ml\ml\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 787, in _apply_op_helper
    op_def=op_def)
  File "C:\Users\shivam.agarwal\ml\ml\lib\site-packages\tensorflow\python\framework\ops.py", line 3290, in create_op
    op_def=op_def)
  File "C:\Users\shivam.agarwal\ml\ml\lib\site-packages\tensorflow\python\framework\ops.py", line 1654, in __init__
    self._traceback = self._graph._extract_stack()  # pylint: disable=protected-access

InvalidArgumentError (see above for traceback): TensorArray decode_raw_image/TensorArray_1_0: Could not write to TensorArray index 2 because the value shape is [383463] which is incompatible with the TensorArray's inferred element shape: [292800] (consider setting infer_shape=False).
     [[Node: decode_raw_image/while/TensorArrayWrite/TensorArrayWriteV3 = TensorArrayWriteV3[T=DT_UINT8, _class=["loc:@decode_raw_image/while/DecodeRaw"], _device="/job:localhost/replica:0/task:0/device:CPU:0"](decode_raw_image/while/TensorArrayWrite/TensorArrayWriteV3/Enter, decode_raw_image/while/Identity, decode_raw_image/while/DecodeRaw, decode_raw_image/while/Switch_1:1)]]


Process finished with exit code 1
  

传递一个参数来检查用户是否在我的帐户中创建了权限   原因

Route::get('/access', ['middleware' => 'hasroles:super,admin', function () {
}]);

中间件:

  

1。使用参数

Route::middleware('admin')->namespace('Admin')->prefix('admin')->group(function(){
    Route::get('/home', 'MainController@getIndex')->name('admin.index')->middleware("hasrole:create");
  

2。使用var-arg

public function handle($request, Closure $next, $parm1, $parm2){}

双向中间件使用

  

1:注册routeMiddleware

public function handle($request, Closure $next, $parm1, $parm2){}
public function handle($request, Closure $next, ...$parm1){}

使用:

// Within App\Http\Kernel Class...
protected $routeMiddleware = [
    'hasrole' => \Illuminate\Auth\Middleware\HasRole::class,
  

2:未在routeMiddleware中注册

使用:

Route::get('admin/profile', function () {
})->middleware('hasrole'); 

答案 3 :(得分:0)

将参数发送为字符串,例如

Route::prefix('panel')->middleware('auth:admin|editor')->group(function (){
    Route::get('/', [SiteController::class, 'index'])->name('site.index');
}

中间件中的程序,以将该字符串感知为数组

if (in_array(Auth::user()->rule, explode('|', $access))) {
   return $next($request);
} else {
   return redirect()->route('site.denied');
}