A Beginner Guide for Laravel Validation

When we build a website in Laravel, we must know about Laravel validation. Laravel provides a different way to validate your incoming data. In this article, we study some basics of Laravel Validations.

While building an application, we should apply client-side and server-side validations without fail. By doing so we can protect our application from unnecessary data. As a result, it will save us a lot of time clearing waste data from the application.

Having said that, let’s take a look at how to apply Laravel validation in your application.

For our tutorial, we take an example form that has 2 fields title and description. We will apply validation and if the validation fails it will display in our view.

Laravel Validation

To get started, we need to include the below statement in our controller file.

use Validator;

Place this statement before the start of your controller like below.

<?php
 
namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use Validator;
 
class PostController extends Controller
{
   .....
}

Before writing the actual validation code, let’s come to the view file. We create a simple form with 2 fields title and description.

<form action="{{ url('post') }}" method="post">
  <div class="form-group">
      <label for="exampleInputTitle">Post Title</label>
      <input type="text" name="title" id="exampleInputTitle" />
  </div>
  <div class="form-group">
      <label for="exampleInputBody">Post Body</label>
      <textarea class="form-control" name="body" id="exampleInputBody" rows="10"></textarea>
  </div>
  {{ csrf_field() }}
  <button type="submit" class="btn btn-default">Submit</button>
</form>

When we submit a form it will give a call to the store() method of our controller. In your case maybe your method is different. So in our method, we will write the validation code as follows.

public function store(Request $request)
{
    $validator = Validator::make($request->all(), [
        'title' => 'required|max:255',
        'body' => 'required',
    ]);
 
    if ($validator->fails()) {
        return redirect('post/create')
                    ->withErrors($validator)
                    ->withInput();
    }
 
    //safe to proceed form
}

You can notice we passed two keys ‘title’ and ‘body’. These are the name of our form elements. Here, Laravel checks if both fields are not empty and title fields do not exceed 255 characters.

If any of the validation fails user will redirect to the page we passed to a redirect() method.

Display Error Messages in a View

We have applied server-side validation. Now let’s take a look at how to display error messages.

Let’s say validation fails in our case and now we need to display error messages on our form. There are 2 ways to display the errors in Laravel views. In the first way, we can display all error messages together at the top of a form. The second way, one can display it next to each field which has an error.

To display the error message at the top of the form add the below code above the form tag.

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

This code will display the error message as shown in the screenshot below:

Error Message

The second way is to print the error message after each field. In that case, our code is as follows:

<div class="form-group">
   <label for="exampleInputTitle">Post Title</label>
   <input type="text" name="title" id="exampleInputTitle" />
   @if ($errors->has('title'))
       <span class="error">
           {{ $errors->first('title') }}
       </span>
   @endif
 
</div>
<div class="form-group">
   <label for="exampleInputBody">Post Body</label>
   <textarea class="form-control" name="body" id="exampleInputBody" rows="10"></textarea>
   @if ($errors->has('body'))
       <span class="error">
           {{ $errors->first('body') }}
       </span>
   @endif
</div>

Notice we are using @if ($errors->has('title')) to check if the ‘title’ field has a validation error. If this field has an error then we print it using {{ $errors->first('title') }}. The same logic we applied for the field ‘body’. Have a look at the below screenshot of this type.

error message

We hope you understand how to apply Laravel validation in your application. Please share your thoughts in the comment section below.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

Leave a Reply

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