Laravel

Laravel Validation with Example

January 30, 2018

author:

Laravel Validation with Example

Validation is one of the fundamental elements of any application. Laravel Framework provides several approaches to validate incoming user data. ValidatesRequests Trait is used by Laravel’s Base Controller to validate incoming HTTP requests. It also supports a variety of powerful rules.

# Adding Validations

To add validation logic to check user data, we use validate method provided by the Illuminate\Http\Request object. This is because we can fetch user input data with Request class.

The code continues execution normally if the validation rules pass. But if the validation fails, an exception is thrown and the user is informed with an automatic error message. For a better perspective, let us write some validation rules:

# controller

public function store(Request $request)
{
    $request->validate([
        'title' => 'required|unique:posts|max:255',
        'category' => 'required',
    ]);
    ...
}

# Exception on First Validation Failure

In certain use cases, we may realize that there’s no requirement of checking the validations further if it encounters failure in between. In such situation, we can assign bail rule:

# controller

public function store(Request $request)
{
    $request->validate([
        'title' => 'bail|required|max:255',
        'category' => 'required',
    ]);
    ...
}

In the above example, if the title is empty, the max rule will not be checked at all. Also, it is important to note that such rules are validated in order of their assignment.

# Validating Nested Parameters

In case HTTP layout or request comprise of nested parameters, we can specify them with a “.“(dot) operator in the validation rules like:

# controller

public function store(Request $request)
{
    $request->validate([
         'title' => 'required|max:255',
         'author.name' => 'required',
         'author.contact' => 'required',
    ]);
    ...
}

# Displaying Validation Errors

The next step is to determine a way to handle exceptions thrown on validation failures. As we discussed earlier, Laravel automatically sends an error message. It also redirects the user to the previous location where the error is supposed to be rectified. Additionally, Laravel also flashes these messages on sessions so that we can have global access to them amidst controllers and layout views.

This eliminates the need to explicitly bind the error messages to views or routes. Laravel keeps a check on session error data and automatically binds them to views if available.

Let us see how we can utilize these session error messages to display to our users through views:

# blade

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

As you can notice above, we have used $errors variable. It is the instance Illuminate\Support\MessageBag which stores session error messages and provides various methods to work with error messages.

# Custom Error Messages

Laravel also supports customizing the error messages for form request. All we have to do is override the messages method and return an array to rule pair and respective error messages:

# controller

public function messages()
{
   return [
       'title.required' => 'Post title is required',
       'category.required'  => 'Oops! Post category missing...',
   ];
}

Parting Thoughts:

With a need of user inputs, the need for validation follows. Laravel makes this implementation much simpler nevertheless as a Laravel developer; you must know to work with all scenarios. In this post, we discovered some really cool features of Laravel like error messages.

Leave a comment

Your email address will not be published. Required fields are marked *