Aejg
Aejg

Reputation: 81

How do I show custom error messages with Laravel form requests?

I am new to Laravel, and have made a UserRequest class that handles validating incoming sign up requests. This is what I have inside it:

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'firstname' => 'required|string',
            'lastname' => 'required|string',
            'email' => 'required|email',
            'password' => 'required|string|min:6',
        ];
    }

    /**
     * Custom message for validation
     *
     * @return array
     */
    public function messages()
    {
        return [
            'firstname.required' => 'First name is required!',
            'lastname.required' => 'Last name is required!',
            'email.required' => 'Email is required!',
            'password.required' => 'Password is required!'
        ];
    }

My question is do these error messages automatically show if the user doesn't enter a field, or is there anything else I need to do, ie in my controller?

Thanks!

Upvotes: 0

Views: 132

Answers (1)

MrEvers
MrEvers

Reputation: 1072

you must include the UserRequest in your controller e.g.

use App\Http\Requests\UserRequest;

And make sure you define your incoming request as a UserRequest (and not a regular Laravel Request) e.g.

public function update(UserRequest $request)

The validation should then be performed automatically.

Upvotes: 3

Related Questions