dev3 ·
I created a form request with php artisan make:request StorePostRequest, type-hinted it in my controller, and every submit returns 403 "This action is unauthorized". My rules() method looks fine. What is wrong?
0
DEV3 Developer Forum
Every post is reviewed first. Usually reviewed within 24 hours.
I created a form request with php artisan make:request StorePostRequest, type-hinted it in my controller, and every submit returns 403 "This action is unauthorized". My rules() method looks fine. What is wrong?
The generated form request has an authorize() method that returns false by default, so it rejects every request before validation runs.
class StorePostRequest extends FormRequest
{
public function authorize(): bool
{
return true; // or a real check
}
public function rules(): array
{
return [
'title' => ['required', 'string', 'max:150'],
'body' => ['required', 'string'],
];
}
}
In recent versions the stub returns false in authorize() (older ones returned true), so always set it deliberately.
Do real authorization here
public function authorize(): bool
{
return $this->user()->can('update', $this->route('post'));
}
Keep one rule: authorize the actor, validate the data.
Handy extras
protected function prepareForValidation(): void
{
$this->merge(['slug' => Str::slug($this->title)]);
}
public function messages(): array
{
return ['title.required' => 'Please give the post a title.'];
}
protected function failedAuthorization()
{
throw new AuthorizationException('Not your post.');
}
Pitfalls
Accept: application/json) it returns 422. If you get a redirect from an API, the client is missing the Accept header.$request->validated() contains only validated keys; safe()->only([...]) and safe()->except([...]) select subsets.Rule::requiredIf(fn () => ...), sometimes, and exclude_if.See the JSON form schema validation snippet for data-driven rule sets.