Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Errors "This action is unauthorized." using Form Request validations in Laravel 5.5+, 6, 7, 8

Tags:

I make some gate like this:

Gate::define('update-post', function  ($user, Post $post) {     return $user->hasAccess(['update-post']) or $user->id == $post->user_id; }); 

I checked my database and it has update-post access and the user id is same as in the post. but I got:

This action is unauthorized.

errors. so am I do some mistake here? thanks.

like image 923
Ying Avatar asked Nov 06 '17 02:11

Ying


1 Answers

I had a similar problem some time ago when starting to use Form Request classes for data validation. I noticed the following:

If you are using Form Requests to validate data, then first of all, check that you set properly the authorization rule that will allow it to pass. This is handled by the authorize() method that must return a boolean, that by default is set to false:

namespace App\Http\Requests\Users;  use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Auth;  class UpdateUserRequest extends FormRequest {     /**      * Determine if the user is authorized to make this request.      *      * @return bool      */     public function authorize()        {         /**           * By default it returns false, change it to           * something like this if u are checking authentication          */         return Auth::check(); // <------------------          /**           * You could also use something more granular, like          * a policy rule or an admin validation like this:          * return auth()->user()->isAdmin();          *           * Or just return true if you handle the authorization          * anywhere else:          * return true;          */      }      public function rules()     {         // your validations...     }  } 
like image 104
Kenny Horna Avatar answered Sep 20 '22 09:09

Kenny Horna