【问题标题】:Cannot Delete using Laravel Resource Controller,( This action is unauthorized )无法使用 Laravel 资源控制器删除,(此操作未经授权)
【发布时间】:2016-06-19 15:42:22
【问题描述】:

我正在尝试使用 Laravel 资源调用 delete 方法,但是我做不到,我不断收到

"此操作是未经授权的错误"

这是我的文件

routes.php

Route::resource('/types','TypeController');

TypeController.php

 public function __construct()
{
    $this->middleware('auth');
}

public function destroy(Request $request, Type $type){
    $this->authorize('destroy',$type);
    $type->delete();
    return redirect('/types');
}

TypePolicy.php

class TypePolicy
{

  public function destroy(User $user, Type $type){
     return $user->id === $type->user_id;
  }

}

AuthServiceProvider.php

protected $policies = [
    'App\Model' => 'App\Policies\ModelPolicy',
    'App\Type' => 'App\Policies\TypePolicy',
];

查看

{{ Form::open(array('route' => array('types.destroy', $type), 'method' => 'post')) }}
 {{ csrf_field() }}
<input type="hidden" name="_method" value="DELETE">
<button type="submit" id="delete-type-{{ $type->id }}" class="btn btn-danger">Delete</button>
{{ Form::close() }}

【问题讨论】:

    标签: php laravel authentication resources


    【解决方案1】:

    路由参数名称必须与您的方法上的参数名称匹配,隐式绑定才能起作用。 Route::resource 的第一个参数是资源名称,也用于路由的“参数”名称。

    你的路由参数是'types',你的方法参数是'type'。

    如果您仍然希望 URL 为“types”但参数为“type”,您可以告诉路由器将资源路由参数设为单数。

    RouteServiceProvider@boot

    public function boot(Router $router)
    {
        $router->singularResourceParameters();
    
        parent::boot($router);
    }
    

    现在,您的 URI 将类似于 types/{type},它将与您的方法签名中的 Type $type 匹配。

    如果您不想将所有资源路由参数设为单数,也可以仅针对该资源执行此操作。

    Route::resource('types', 'TypeController', ['parameters' => 'singular']);
    

    Laravel Docs - Controllers - Restful - Naming Resource Route Paramters

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-20
      • 2019-05-04
      • 1970-01-01
      • 1970-01-01
      • 2020-11-19
      • 1970-01-01
      • 1970-01-01
      • 2022-01-11
      相关资源
      最近更新 更多