Laravel Custom FormRequest Class Causes Unexpected 302 Redirect

  laravel, laravel-8, laravel-formrequest

I have a strange issue. When submitting a POST request I get a 302 redirect back to the create form, with message of any kind.

It seems most unexpected redirects are csrf related issues. I am certain that is not the case here.

I can confirm it only happens when I use a customer FormRequest class to validate the request, and if I just use the standard Request Class it works just fine.

This works:

public function store(Request $request)

This causes the random 302 redirect:

use AppHttpRequestsCreatePageRequest;
public function store(CreatePageRequest $request)

For its part CreatePageRequest looks fine as far as I can tell:

<?php

namespace AppHttpRequests;

use IlluminateValidationRule;
use IlluminateFoundationHttpFormRequest;

class CreatePageRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'title' => ['required', 'string'],
            'sub_title' => ['required', 'string'],
            'created_date' => ['required', 'date'],
            'body' => ['nullable', 'string'],
            'user_id' => ['required', 'integer', 'exists:users,id'],
            'status' => ['required', Rule::in(['Draft', 'Pending Review', 'Rejected', 'Published'])],
            'category_id' => ['nullable', 'integer', 'exists:categories,id'],
            'type' => ['required', Rule::in(['Page', 'Sub-Page', 'Section'])],
            'publish_date' => ['nullable', 'date'],
        ];
    }
}

When using my CreatePageRequest class the store function in the controller would never get to fire, a dd('test'); in the first line of the store method never fired. But using a standard Request causes everything to work fine, expect for validation obviously.

Any ideas what would cause this?

Source: Laravel

Leave a Reply