Laravel 8/7 Validation Tutorial : Laravel To-Do Part 2

By Parth Patel on Feb 10, 2020

When working with user data, data validation is very important. Normally you would have to write complex data validation from scratch while building web application. But Laravel comes with great validation library thereby making whole validation process very easy and straightforward.

In this tutorial, we will learn how to utilize form data validation in Laravel 7 while working with user inputs of different types as well as displaying error messages.

laravel validation tutorial

First, we will discuss various types of form inputs and its validation in Laravel with general examples. Then we will write validation for our to-do application.Let's learn about Laravel form validation by working on our to-do application as an example.

Laravel Form Validation

Laravel provides Validator class which provides various functions and rules for the same. Of course, there are various ways to use Validator class in a web application but we will focus only on controller method which is common and most used way.

Let's write validation for our "Add Task" page. We want to make sure, the task description is not empty (There is no meaning in storing empty tasks, right?).

1) Update TasksController.php

Add validation logic for task description in create method. Code should look like below:

Here 'description' resembles the field name you pass from the form in blade file while 'required' is the validation rule which means the data is required and cannot be empty. There are other validation rules too which you can find below.

public function create(Request $request)
    {
        $this->validate($request, [
            'description' => 'required'
        ]);
    	$task = new Task();
    	$task->description = $request->description;
    	$task->user_id = Auth::id();
    	$task->save();
    	return redirect('/'); 
    }

Now, if you try to add an empty task, it will redirect back to it.

Make same changes to update method too.

public function update(Request $request, Task $task)
    {
    	if(isset($_POST['delete'])) {
    		$task->delete();
    		return redirect('/');
    	}
    	else
    	{
            $this->validate($request, [
                'description' => 'required'
            ]);
    		$task->description = $request->description;
	    	$task->save();
	    	return redirect('/'); 
    	}    	
    }

2) Update blade files to display error messages

You have added validation logic above but you also need to show error messages in view so user can understand what's the issue.

Make changes to add.blade.php as below:

<div class="form-group">
        <textarea name="description" class="form-control"></textarea>  
        @if ($errors->has('description'))
            <span class="text-danger">{{ $errors->first('description') }}</span>
        @endif
    </div>

Also on edit.blade.php:

<div class="form-group">
		<textarea name="description" class="form-control">{{$task->description }}</textarea>	
		@if ($errors->has('description'))
            <span class="text-danger">{{ $errors->first('description') }}</span>
        @endif
	</div>

It will show error message like below if you try to add empty task.

Now, run your app and try submitting form with empty description.

So, for our to-do app, we only need one validation but generally many different types of validation are needed.Below, I will try to explain some of the common validation rules. For more detailed list, you can check Laravel Documentation.

Laravel Validation Rules

Below is the list of some common laravel validation rules. Remember, you can combine multiple rules to one field.

  • required - Data is required and cannot be null
  • date - Data must be a valid date according to the strtotime PHP function
  • before:date - Date must be before the given date
  • between:min,max - Data must be number between given minimum and maximum
  • email - Data must be a valid email format
  • min:number - Data must be more than or equal to given number
  • unique:table,column,except,idColumn - Data must be unique among given table

Check the example below. It is a validation example for user registration form.

$this->validate($request, [
            'name' => 'required',
            'password' => 'required|min:8',
            'email' => 'required|email|unique:users',
        ]);

So, this is how we can use Laravel's validator feature to easily incorporate input validation with default error messages.