Request validation does not work in Laravel 5.4

In MyRequest :

public function authorize()
{
    return true;
}
public function rules()
{
    switch($this->method())
    {
        case 'GET':
        case 'DELETE':
        {
            return [];
        }
        case 'POST':
        {
            dd('here working'); // if remove this line, it does not working, page just like refesh
            return [
                'name' => 'required',
                'price' => 'required',
            ];
        }
        case 'PUT':
        case 'PATCH':
        {
            return [
                'name'      => 'required',
                'price'     => 'required',
            ];
        }
        default:break;
    }
}

In my controller:

public function store(MyRequest $request)
{
}

I checked sure that app run into dd() function in case "POST". But, if i remove this line (dd() function), page like refresh, it did not validate data.

1 answer

  • answered 2018-01-13 17:26 Jeffrey Westerkamp

    Actually I think it did validate your data. Check for the response code in your browser devtools after form submission. if the status code is 302, chances are that there is a variable Illuminate\Support\MessageBag $errors available in the template that the response came with. How to use $errors is explained here.

    If validation fails, Laravel typically redirects you back to the previous page (the form page in this case) with a status code of 302, and additionally injects the variable $errors into the template for you to display the messages to the user. Paste the following in your blade template next to the form you're working on, and you might find out it is not quite a page refresh after all:

    @if ($errors->any())
        <div class="alert alert-danger">
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif