Various way of Laravel Validation

Various way of Laravel Validation

Form validation is a very important fact for sanitizing and protecting unwanted data into our application. For validation, The Laravel Framework provides simpler, easy and effective validation rules for validating user form request and sanitizing unwanted data. In this post, I'll show you the various way of Laravel validation for validating user form request. After each method discussion, I'll tell you when which method is preferable.

 

Different ways of Laravel Validation

  1. Controller Validation
  2. Request Validation
  3. Model Validation
  4. Manual Validation

 

1. Controller Validation

In this method, we can validate our user submitted form request directly into our controller method by $this->validate() method. Generally, most of the developers are used to this method. In this method, if validation is not passed then it'll automatically redirect back with all validation errors. Let's take an example.

<?php namespace App\Http\Controllers;

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

class PostController extends Controller
{
   
    public function store(Request $request)
    {
    	$rules = ['title' => 'required|min:10', 'description' => 'required'];
        $this->validate( $request, $rules);

        // validated, now do your code

    }
}

Note: This method is easy and clean. It's suitable when your user-submitted form input is a minimum and small project. If your form request input is not more than 3-5 then it's recommended. Not complex things all are in one place.

 

2. Request Validation

In this method, we can validate our user form request by making a separate form request validation class. It's a re-usable way. We have to make the form request validation class with our required validation rules and inject the class instance where we have required to validate user form request. Let's take an example.

Make form request class by artisan command

php artisan make:request PostRequest

PostRequest class

<?php namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class PostRequest extends FormRequest
{

    public function authorize()
    {
    	// we can check more things 
        return true;
    }

    public function rules()
    {
    	return [
    		'title'=> 'required|min:10',
    		'post_status'=> 'required|in:Published,Draft,Pending',
    		'description' => 'required'
    	];
    }

}

If we want to use same form request class for different HTTP request like POST, PUT, PATCH, DELETE then we can write our form request like below.

<?php namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class PostRequest extends FormRequest
{

    public function authorize()
    {
    	// we can check more things 
        return true;
    }

    public function rules()
    {
		switch ($this->method()) {
		    case 'GET':
		    case 'DELETE': {
		        return [
		        	'id'=>'required|exists:posts,id'
		        ];
		    }
		    case 'POST': {
		        return [
		    		'title'=> 'required|min:10',
		    		'description' => 'required'
		        ];
		    }
		    case 'PUT':
		    case 'PATCH': {
		        return [
		        	'id'=>'required|exists:posts,id'
		    		'title'=> 'required|min:10',
		    		'description' => 'required'
		        ];
		    }
		    default:
		        break;
		}
    }

}

Our re-usable form request class is ready to use where we need it.

<?php namespace App\Http\Controllers;

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

use App\Http\Requests\PostRequest;

class PostController extends Controller
{
   
    public function store(PostRequest $request)
    {
        // validated, now do your code

    }

    public function update(PostRequest $request)
    {
        // validated, now do your code

    }
}

Note: Request validation by making a validation form request class is the re-usable and more maintainable way. It's recommended when your project going medium to large scale and form input is more than 2/3.

 

3. Model Validation

In this method, we can do all our validation stuff inside our model. Let's take an example.

Inside model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Validator;

class Post extends Model
{

    protected $rules = array(
        'title'=> 'required|min:10'
    );

    public function validate($inputs) {
        $v = Validator::make($inputs, $this->rules);
        if($v->passes()) return true;
        $this->errors = $v->messages();
        return false;
    }
}

In our controller

<?php namespace App\Http\Controllers;

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

class PostController extends Controller
{
   
    public function store(Request $request)
    {
        $post = new Post();
        if(!$post->validate($request->all())) return redirect()->back();

        // do your code

    }

}

Note: This is another way for validation. Still, I'll recommend method 2.

 

4. Manual Validation

This is a manual validation process with Laravel validation facade class. Suppose we have to validate excel import data. During excel upload, a user just uploads an excel file with no input field. That time we have to validate our user excel data via laravel validation facade class manually. Let's take an example.

$rules = [
    'id' => "required|exists:users,
    'name' => 'required'
];

foreach ($excelRows as $key => $row) {
    
    $validator = Validator::make($row, $rules);

    if ($validator->fails()) {
        $isValid = false;
        break;
    } else {
        $isValid = true;
    }
}

Note: Sometimes we need to validate some custom data. That time this is a very handy and useful process to validate our custom user data with Laravel validation rules via validation facade class.

 

Conclusion

By default, Laravel has very powerful and handy validation rules. We have to just use it according to our application need. In this post, I have tried my best to show you different ways of Laravel Validation. I hope this post will help you to understand the Laravel validation process. If this post helpful to you then please share it other. 


Share

Related Post


Laravel Simple Filemanager

Speed Up Laravel website - Step by Step

Repository Design Pattern in Laravel

Laravel desktop application using Electron Js

Top 10 question-answer for New Laravel developer

Laravel Excel import export