Form validation in Laravel

 

Form Validation is an extremely important part in every web application.It protects your incoming data from malicious attacks.So before you save user input data into the database or send an email to the user you should always properly validate your form.

There are 2 different ways to validate the form i.e Client Side Validation and the Server Side Validation. Using client side validation, the browser does not send any data to the server it validates by itself. The main problem when using client side validation is that suppose if someone has disabled the javascript in the browser then validation will not work. So I suggest not to rely on client side validation. Another one is Server Side validation, in this method the browser sends user input value to the server and validates the form using your server side scripting language and sends back the response to the browser.

In this article, I will describe how to validate a form in laravel 5. Laravel has very strong validation methods and it is very easy to use. To validate incoming HTTP request, by default the base controller’s class of Laravel use ValidatesRequests trait. We can validate our form with different methods. Let’s start now.

Routes:
Define your routes in app/Http/routes.php file.

//This will display the registration form
Route::get('user/register', 'UserController@register');

//Store User Data
Route::post('user/register', 'UserController@SaveData');

In the above code get route will show the registration form while post route will validate the form and store the data in the database.

Below are the basic validation features of laravel. You can validate your form in 2 different ways.

Controllers:
Create the UserController.php controller file under “app/Http/Controllers/UserController.php” and add the below code in your controller.

<?php 
 namespace App\Http\Controllers;
 use Illuminate\Http\Request; 
 use App\Http\Controllers\Controller; 

 class UserController extends Controller{ 

  /*This method will display the registration form*/ 
  public function register() { 
    return view('user.register'); 
  } 

  /*This method will validate the form and store the data in database*/ 
  public function SaveData(Request $request) { 
       $this->validate($request, [
        	'fname' =>'required',
        	'lname' =>'required',
		'email' =>'required|email',
   		]);
		
		//Write your code for saving in database
	}
}
?>

In the above code validate() method is used by the ValidatesRequests trait. The validate() method receives all incoming HTTP request and check the validation rules. It will proceed normally if validation rules pass, if validation rules fail an exception will be thrown. If you have not defined your custom error messages for your rules then laravel will automatically generate default error messages and it will send back to the user. You can define multiple rules using pipe(|) character as I have defined in the above code.

Blade Template:
Now create your “register.blade.php” template file under “resources/views/user/register.blade.php”. In the above SaveData method we didn’t bind the error message to any variable because laravel always checks in the session data for errors, if found then it automatically binds them to the view file and stores in the $errors variable. Add the below code in your register.blade.php template file.

{!! Form::open(['method' => 'post']) !!}          
  @include('errors.error')
  <h2>Sign Up</h2>
  <div> 
  	{!! Form::text('fname',Request::old('fname'),['placeholder'=>'First Name') !!}
  </div>
  <div>
    {!! Form::text('lname',Request::old('lname'),['placeholder'=>'Last Name']) !!}	  
  </div>  
  <div>
   {!! Form::text('email',Request::old('email'),['placeholder'=>'Email']) !!}	  
  </div>
  <br />
  <div>
    {!! Form::submit('Register') !!} 
  </div>
  {!! Form::close() !!}

Error Template File:
In the above code we have included this line i.e @include(‘errors.error’). You can show all error messages to the user with different ways.If you want to use all error messages globally then create a template file under “resources/views/errors/error.blade.php” and add the below code. Then include this error template file wherever you want to show the error messages. In other way you can use below code on your template file.The most beneficial way to separate the file is you just include the file only once. you don’t need to write same code again and again on every template file.

@if (count($errors) > 0)
    <div>
        <ul>
            @foreach ($errors->all() as $error)
                <li>{!! $error !!}</li>
            @endforeach
        </ul>
    </div>
@endif

Manual Form Validation in Laravel

Using this method you can create your validator manually. The make() method on the Validator facade generates a new validator instance.

Controller:
Earlier you have already created your controller. Now paste the below code on your controller.

<?php
namespace App\Http\Controllers;
use Validator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    
    /*This method will display the registration form*/
	public function register()
    {
        return view('user.register');
    }
	
	/*This method will validate the form and store the data in database*/
	public function SaveData(Request $request)
    {
        $messages = ['fname.required' => 'Please enter first name.',
					 'lname.required' => 'Please enter your last name.',
					 'email.required' => 'Please enter your email address.',
					 'email.email' => 'Please enter a valid email address.'
					];
						
		$validator = Validator::make($request->all(), [
            'fname' => 'required',
            'lname' => 'required',
			'email' => 'required|email'
        ],$messages);

        if ($validator->fails()) {
            return redirect('user/register')
                        ->withErrors($validator)
                        ->withInput();
        }
		
		//Write your other stuff here
    }
}
?>

Here we have used laravel’s make() method for data validation. The make method can accepts upto 4 parameters. Here we have used only 3. The first and the second parameters are mandatory. First parameter should be your incoming post data, second parameter is your validation rules and third parameter which is optional should be your custom error message. If validator’s fails() method failed to validate, then withErrors() method is used to flash the error message to the session. withInput() is used to flash the input data to the session. As I have already described above, $errors variable error message will automatically available in your template file which will display the error message to the user. The withErrors() method can accept upto 2 parameters where first parameter is a MessageBag or an array. You can use second parameter where you have more than one form in a single page. Simply by passing a name, you can retrieve the error message on the template file like below :

return redirect('user/register')->withErrors($validator, 'register');

Laravel Form Validation With Form Request

The last validation rules is Form Request Validation. This is a custom request class which contains all your validation rules. To create form request class you can use make:request Artisan CLI command or you can create the file manually.

php artisan make:request SaveRegisterPostRequest

Above command line will generate a Form Request class file under “app/Http/Requests” directory. If you have created the file using Artisan CLI command then the form request class automatically contains 2 methods authorize() and rules(). If you have manually created the file then you need add these 2 methods or it will through an error. This class validates the incoming form request before any controllers method will called. authorize() is another method which is used by the form request class, it checks whether authenticated user has priviledge to update any resource.

Inside the authorize() method, if you want to validate authenticated user from your database for privileges, then you can write your code here. If you want your authentication logic somewhere in your application then return true from the authorize method. It returns 403 status code if authorize() method returns false and controller method will not execute. You can defined all your rules inside the rules() method.

The form request class contains below code.You can customize all your validation message in the messages() method else laravel will use it’s default message.

<?php 
namespace App\Http\Requests;
use App\Http\Requests\Request;

class SaveRegisterPostRequest extends Request {

	/**
	 * It checks if the user is authorized to make this request.
	 *
	
	 */
	public function authorize()
	{
		return true;
	}

	/**
	 * Mention all your validation rules here
	 *	 
	 */
	public function rules()
	{
		return ['fname' => 'required',
                'lname' => 'required',
			    'email' => 'required|email'
		];
	}

	public function messages()
	{
		return ['fname.required' => 'Please enter first name.',
				 'lname.required' => 'Please enter your last name.',
				 'email.required' => 'Please enter your email address.',
				 'email.email' => 'Please enter a valid email address.'
				];
	}

}
?>

Customize Flash Error Message Format in laravel

When validation fails laravel flashes the error message to the session. If you want to customize the error message format then override the formatErrors() method on your “App\Http\Requests\Request\Request.php” file. Always import the Illuminate\Contracts\Validation\Validator class at the top of the file when you want to customize the flash error message, or it will return an error. Now your base request class will look like below code:

<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;

abstract class Request extends FormRequest
{
   
   protected function formatErrors(Validator $validator)
	{
		return $validator->errors()->all('<div style="color:red;">:message</div>
                       <div style="clear:both;"></div>');
	}

}
?>

Now you need to modify your error template file. Remove all div and ul tag because we have defined our message format on our form request base class.

@if (count($errors) > 0)	
	@foreach ($errors->all() as $error)
		{!! $error !!}
	@endforeach
@endif

Controller:

<?php 
namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Requests\SaveRegisterPostRequest;
use Illuminate\Http\Request;

	public function register(){
		return view('user.register');		
	}
	
	/*Save data in the database*/
	public function SaveData(SaveRegisterPostRequest $request){
		//Write your code here to save data in the database
	}
?>

If validation fails then it will automatically redirects to register template page and display all error messages.

For more tutorials stay in touch with us.

COMMENTS ( 18 )

Rhoda says:

Nice post. I learn something totally new and challenging
on blogs I stumbleupon everyday. It’s always helpful to read through articles
from other authors and practice something from their sites.

Reply

ADHD says:

Hi there, I check your blogs daily. Your humoristic style is witty, keep up the good work!

Reply

Hi there Dear, are you truly visiting this web page on a regular basis,
if so then you will without doubt get fastidious experience.

Reply

This is really attention-grabbing, You are an overly professional blogger.
I have joined your feed and sit up for seeking more of your magnificent post.
Additionally, I’ve shared your web site in my social
networks

Reply

quest bars says:

I’m really impressed with your writing skills as well as with the layout on your blog.
Is this a paid theme or did you customize it yourself?
Either way keep up the excellent quality writing, it is
rare to see a nice blog like this one nowadays.

Reply

quest bars says:

Unquestionably believe that which you said.
Your favorite justification seemed to be on the net the simplest thing to be aware
of. I say to you, I definitely get irked while people think about
worries that they just do not know about.
You managed to hit the nail upon the top and also
defined out the whole thing without having side-effects , people can take a signal.
Will likely be back to get more. Thanks

Reply

Hi there to all, it’s really a fastidious for me to pay a quick visit this website,
it contains helpful Information.

Reply

FlorUYauck says:

Quality articles or reviews will be the secret to attract the visitors to visit
the site, that’s what this website is providing.

Reply

Nice post. I was checking continuously this blog and
I am just impressed! Extremely helpful information specially the last part :) I
take care of such info much. I found myself seeking this certain information for any very long
time. Thanks a lot and better of luck.

Reply

Its like you read my mind! You appear to know
a lot about this, like you wrote the book in it or something.
I think that you can do with some pics to drive the message
home a bit, but other than that, this is wonderful blog.
A fantastic read. I will certainly be back.

Reply

Leave a comment

SUBSCRIBE TO NEWSLETTER

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Categories