Laravel Validation

Manish Chaudhary
ISOP Nepal
Published in
2 min readMay 9, 2020

Laravel form validation and many more.

I this post we will learn how to add validation logic to our code, also form requests that separate validation logic from controller.

To start this post lets assume we have tasks module where we have two routes for create and store where create route shows form to save task and store route actually stores the task.

So we create TaskController where code will look like this.

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class TaskController extends Controller
{
/**
* Show the form to create a new task post.
*
* @return Response
*/
public function create()
{
return view('task.create');
}

/**
* Store a new task post.
*
* @param Request $request
* @return Response
*/
public function store(Request $request)
{

}
}

Writing Validation Logic

$validated = $request->validate([
'title' => 'required|unique:tasks|max:255',
'body' => 'required',
]);

After writing validation logic store function will look like this.

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

Displaying validation error

<h1>Create Task</h1>

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

Find whole lot of validation rules available in this link.

We can also separate validation logic in different class called FromRequest.

We can create form request using this command.

php artisan make:request StoreTaskRequest

This command creates StoreTaskRequest class file in app\Http\Requests Then we write validation logic in rules function of StoreTaskRequest class

public function rules()
{
return [
'title' => 'required|unique:taskss|max:255',
'body' => 'required',
];
}

Now the controller will look like this

public function store(ShowTaskRequest $request)
{
// no validation logic here
}

Donot forget to import the ShowTaskRequest class.

Thats all about the basics of laravel validation. We can also create our custom rules and you can find details about it in this link.

--

--

Manish Chaudhary
ISOP Nepal

Software developer and father to a beautiful daughter