无法使用 Laravel 资源控制器删除,(此操作未经授权)
Cannot Delete using Laravel Resource Controller,( This action is unauthorized )
我正在尝试使用 Laravel 资源调用删除方法,但是我做不到,我不断收到
"此操作是未经授权的错误"
这是我的文件
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() }}
路由参数名称必须与您的方法中的参数名称相匹配,隐式绑定才能起作用。 Route::resource
的第一个参数是资源名称,它也用于路由 'parameter' 名称。
你的路由参数是'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
我正在尝试使用 Laravel 资源调用删除方法,但是我做不到,我不断收到
"此操作是未经授权的错误"
这是我的文件
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() }}
路由参数名称必须与您的方法中的参数名称相匹配,隐式绑定才能起作用。 Route::resource
的第一个参数是资源名称,它也用于路由 'parameter' 名称。
你的路由参数是'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