baan
baan

Reputation: 3

Cannot Delete using Laravel Resource Controller,( This action is unauthorized )

I am trying to call delete method using Laravel Resource, however I cannot do that, I keep getting

"This action is unauthorized error"

Here are my files

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',
];

View

{{ 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() }}

Upvotes: 0

Views: 1933

Answers (1)

lagbox
lagbox

Reputation: 50521

The route parameter name has to match the parameter name on your method for implicit binding to work. The first argument to Route::resource is the resource name, which is used for the route 'parameter' name as well.

Your route parameter is 'types' and your method parameter is 'type'.

If you still want the URL to be 'types' but the param to be 'type', you can tell the router to make your resource route parameters singular.

RouteServiceProvider@boot

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

    parent::boot($router);
}

Now your URI would be something like types/{type} which would match Type $type in your method signature.

If you don't want to make all resource route parameters singular, you can do it just for that resource as well.

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

Laravel Docs - Controllers - Restful - Naming Resource Route Paramters

Upvotes: 1

Related Questions