DEV3 Technologies home

DEV3 Developer Forum

Why does my Laravel FormRequest return 403 This action is unauthorized?

Laravel helpSolved0 views
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?

#laravel#validation#forms

0

1 reply

dev3 · Accepted answer

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

  • Validation failure on a normal web request redirects back with errors; on JSON requests (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.
  • Conditional rules: Rule::requiredIf(fn () => ...), sometimes, and exclude_if.

See the JSON form schema validation snippet for data-driven rule sets.

0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.