Laravel Basic Example


Example

You can validate request data using the validate method (available in the base Controller, provided by the ValidatesRequests trait).

If the rules pass, your code will keep executing normally; however, if validation fails, an error response containing the validation errors will automatically be sent back:

  • for typical HTML form requests, the user will be redirected to the previous page, with the form keeping the submitted values
  • for requests that expect a JSON response, a HTTP response with code 422 will be generated

For example, in your UserController, you might be saving a new user in the store method, which would need validation before saving.

/**
 * @param  Request  $request
 * @return Response
 */
public function store(Request $request) {
    $this->validate($request, [
        'name' => 'required',
        'email' => 'email|unique:users|max:255'
    ],
    // second array of validation messages can be passed here
    [
        'name.required' => 'Please provide a valid name!',
        'email.required' => 'Please provide a valid email!',
    ]);

    // The validation passed
}

In the example above, we validate that the name field exists with non-empty value. Secondly, we check that the email field has a valid e-mail format, is unique in the database table "users", and has maximum length of 255 characters.

The | (pipe) character combines different validation rules for one field.

Sometimes you may wish to stop running validation rules on an attribute after the first validation failure. To do so, assign the bail rule to the attribute:

$this->validate($request, [
    'name' => 'bail|required',
    'email' => 'email|unique:users|max:255'
]);

The complete list of available validation rules can be found in the parameters section below.