Laravel 5 form validation

Rakesh Sharma      2 Comments  

Using Laravel 5 form validation with request and validation class :-

A new version of laravel has been released with named laravel 5. so there is also some changes to validate a form process or using form validation in laravel 5. In this article i am just updating and laravel 4 form validation to laravel 5 form validation in a simple way. A form validation means we forcing user to enter correct data in form field according to our need. Laravel 5 provide a simple, convenient facility for validating data and retrieving validation error messages using Validation class and using request.
In below we are making a fully code to validate a form in laravel using controller. Making a view file which contain form and form for fields and validation error message showing code. In controller we are validating all input and applying validation rules and custom error messages and sending back to view with validation error messages on view. so Let’s create a form to understand how to use form validation in laravel 5. we are using two ways to make laravel 5 form validation.

1. laravel 5 form validation with Form Request

2. laravel 5 form validation with Validation class (old style)

So we will use both way to make form validation in laravel 5. below is a screenshot of form what we are making.

Laravel 5 form validation

1. laravel 5 form validation with Form Request :-

Form validation with Form Request is new way added in laravel 5. we can create controller and requests using artisan commands and make our process easy. Form request class is a custom class which contain validation logic. to understand form validation in laravel 5 with request class let’s start process and create some files.

View :- create a view file named “valid.blade.php” under “resources/views/valid.blade.php” and add below code.


<div class="secure">Register form</div>
{!! Form::open(array('url'=>'blogpost/store','method'=>'POST')) !!}
<div class="control-group">
  <div class="controls">
  {!! Form::text('name','',array('id'=>'','class'=>'form-control span6','placeholder' => 'Please Enter your Name')) !!}
  @if ($errors->has('name'))<p style="color:red;">{!!$errors->first('name')!!}</p>@endif
  </div>
</div>
<div class="control-group">
  <div class="controls">
  {!! Form::text('email','',array('id'=>'','class'=>'form-control span6','placeholder' => 'Please Enter your Email')) !!}
  @if ($errors->has('email'))<p style="color:red;">{!!$errors->first('email')!!}</p>@endif
  </div>
</div>
<div class="control-group">
  <div class="controls">
  AGE : - {!! Form::select('age', array('' => 'Click to select', '20' => '20 years'),array('class'=>'form-control span6')) !!}
  @if ($errors->has('age'))<p style="color:red;">{!!$errors->first('age')!!}</p>@endif
  </div>
</div>
<div class="control-group">
  <div class="controls">
  {!! Form::password('password',array('class'=>'form-control span6', 'placeholder' => 'Please Enter your Password')) !!}
  @if ($errors->has('password'))<p style="color:red;">{!!$errors->first('password')!!}</p>@endif
  </div>
</div>
<div class="control-group">
  <div class="controls">
  {!! Form::password('cpassword',array('class'=>'form-control span6', 'placeholder' => 'Confirm your Password')) !!}
  @if ($errors->has('cpassword'))<p style="color:red;">{!!$errors->first('cpassword')!!}</p>@endif
  </div>
</div>
<div id="success"> </div>
{!! Form::submit('Register', array('class'=>'')) !!}
<br />
{!! Form::close() !!}
</div>

Controller :- Now we need to create a controller we can easily create controller using artisan commands. so let’s create a controller with artisan command. go to your application route and run below artisan command.

php artisan make:controller BlogPostController

This command will create a new controller in “app/Http/controllers/BlogPostController.php” which have more functions but we don’t need now to validate form so add below code in new created controller or you can create it manually with text editor create a controller file named “BlogPostController.php” under “app/Http/controllers/BlogPostController.php” and add below code.


<?php namespace App\Http\Controllers;

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

class BlogPostController extends Controller {
/**
 * Show the form for creating a new resource.
 *
 * @return Response
 */
  public function create() {
    return View('pages.valid');
  }

/**
 * Store a newly created resource in storage.
 *
 * @return Response
 */
  public function store(CreateBlogPostRequest $request) {
    // Getting all data after success validation.
    print_r($request->all());die;
    // do your stuff here.
  }
}

If you open controller file after creation using artisan command you will see more methods so i have removed non-using methods for now and keeping to method create() and store()
create() :- we are using this to show our form.
store() :- using method injection

In BlogPostController we are importing CreateBlogPostRequest class with use “App\Http\Requests\CreateBlogPostRequest” and we are using method injection in store() (public function store(CreateBlogPostRequest $request)).

form validation in laravel 5

Form Request :- Now we need to create a form request class using artisan commands. so let’s create a form request class with artisan command. go to your application route and run below artisan command.

php artisan make:request CreateBlogPostRequest

This command will create a new form request class in “app/Http/Requests/CreateBlogPostRequest.php”.


<?php namespace App\Http\Requests;

use App\Http\Requests\Request;

class CreateBlogPostRequest extends Request {

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

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
  public function rules() {
    return [
      'name' => 'required|alpha',
      'email' => 'required|email',
      'age' => 'required',
      'password' => 'required',
      'cpassword' => 'required',
    ];
  }
}

After open this file you see, by default it consists of two public methods: rules and authorize. rules method stands for apply your validation rules and authorize stands for a check we can apply like user login or any condition we need. Now we need to add our form validation rules in it and make authorize() to true.

Routes :- add below code in “app/Http/routes.php” to make both get and post routes.


Route::get('blogpost/create', 'BlogPostController@create');
Route::post('blogpost/store', 'BlogPostController@store');

Now what this process do:- There is a event listener FormRequestServiceProvider which handle the validation before controller hits so all your validation calls before controller class make it work. so you can say it’s a pre call your application request not hits to controller if any validation fails. if all validation goes fine your controller store() function will be call to further process.

2. laravel 5 form validation with Validation class (old style) :-

In this way we simply adding our form validation rules and validating form in our controller with input request. below we will see how to make form validation in laravel 5 direct in controller class.

View :- create a view file named “valid.blade.php” under “resources/views/valid.blade.php” and add below code.


<div class="secure">Register form</div>
{!! Form::open(array('url'=>'account/formvalidate','method'=>'POST')) !!}
<div class="control-group">
  <div class="controls">
  {!! Form::text('name','',array('id'=>'','class'=>'form-control span6','placeholder' => 'Please Enter your Name')) !!}
  @if ($errors->has('name'))<p style="color:red;">{!!$errors->first('name')!!}</p>@endif
  </div>
</div>
<div class="control-group">
  <div class="controls">
  {!! Form::text('email','',array('id'=>'','class'=>'form-control span6','placeholder' => 'Please Enter your Email')) !!}
  @if ($errors->has('email'))<p style="color:red;">{!!$errors->first('email')!!}</p>@endif
  </div>
</div>
<div class="control-group">
  <div class="controls">
  AGE : - {!! Form::select('age', array('' => 'Click to select', '20' => '20 years'),array('class'=>'form-control span6')) !!}
  @if ($errors->has('age'))<p style="color:red;">{!!$errors->first('age')!!}</p>@endif
  </div>
</div>
<div class="control-group">
  <div class="controls">
  {!! Form::password('password',array('class'=>'form-control span6', 'placeholder' => 'Please Enter your Password')) !!}
  @if ($errors->has('password'))<p style="color:red;">{!!$errors->first('password')!!}</p>@endif
  </div>
</div>
<div class="control-group">
  <div class="controls">
  {!! Form::password('cpassword',array('class'=>'form-control span6', 'placeholder' => 'Confirm your Password')) !!}
  @if ($errors->has('cpassword'))<p style="color:red;">{!!$errors->first('cpassword')!!}</p>@endif
  </div>
</div>
<div id="success"> </div>
{!! Form::submit('Register', array('class'=>'')) !!}
<br />
{!! Form::close() !!}
</div>

Controller :- create a controller file named “AccountController.php” under “app/Http/controllers/AccountController.php” and add below code.


<?php namespace App\Http\Controllers;
use Input;
use Validator;
use Redirect;
class AccountController extends Controller {
  public function formvalidate() {
    // getting all of the post data
    $postData = Input::all();
    // setting up custom error messages for the field validation
     $messages = [
         'email.required' => 'Enter email address',
         'password.required' => 'You need a password',
     ];
    $rules = [
      'name' => 'required|alpha',
      'email' => 'required|email|unique:tablename',
      'age' => 'required',
      'password' => 'required',
      'cpassword' => 'required|same:password',
    ];

    // doing the validation, passing post data, rules and the messages
    $validator = Validator::make($postData, $rules, $messages);
    if ($validator->fails()) {
      // send back to the page with the input data and errors
      return Redirect::to('/account/formvalidate')->withInput()->withErrors($validator);
    }
    else {
	   // Do your stuff here.
      // send back to the page with success message
      return Redirect::to('/account/formvalidate');
    }
  }
}

Routes :- add below code in “app/Http/routes.php”


Route::get('account/formvalidate', function() {return View::make('pages.valid');});
Route::post('account/formvalidate', 'AccountController@formvalidate');

Now describing above code :-

Controller code :-

Getting all form post data as an array in $postData.


$postData = Input::all();

creating custom error messages :-

default laravel 5 provide inbuilt messages for each rules but if we want to use our own custom error messages to validate a form then we need to send messages for each input and each rules as an array and pass it to Validator::make().


$messages = [
  'email.required' => 'Enter email address', // custom message for required rule.
  'email.email' => 'Enter correct email address', // custom message for email rule.
  'password.required' => 'You have to set a password',
]; 

syntax :- array(‘field_name.rule_name’=> ‘your custom message’);

Setting up rules to validate each form field what we need or apply validation rules on each form field. You can apply mutiple rules seperated by |(pipe sign).


$rules = [
  'name' => 'required|alpha', // alpha - only contain letters
  'email' => 'required|email|unique:tablename', // unique:tablename - checking given table form unique email 
  'age' => 'required',
  'password' => 'required',
  'cpassword' => 'required|same:password', //same:password - match with password field
];

syntax :- array(‘field_name’=> ‘rule_name|rule_name|rule_name’);

calling Validator class and passes arguments with inputs and rules and messages. if you don’t want custom error messages no need to pass $messages.


$validator = Validator::make($postData, $rules, $messages);

//Checking if any error on form or form not completed validation rules. 
if ($validator->fails()) {

//Redirecting back to view with all input data and errors.

return Redirect::to('/account/validate')->withInput()->withErrors($validator);

View code :-
If you want all messages on one place add below code to view file :-

errors


@if ($errors->has())
<p style="color:red;">
  @foreach ($errors->all() as $error)
    {!! $error !!}<br />		
  @endforeach
</p>
@endif

Showing validation or first error messages for fields with check If messages exist for a field.


@if ($errors->has('name'))<p style="color:red;">{!!$errors->first('name')!!}</p>@endif

//Syntax :- check if error or validation message exist for field
if ($errors->has('field_name')) {
}

//show first error messages for field.

{!!$errors->first('field_name')!!}

Validating multiple fields in laravel 5 :-

you can validate multiple fields at same time in laravel 5 using multi array.


$validator = Validator::make(
    [
        'name' => 'myname',
        'password' => 'mypass',
        'email' => 'test@example.com'
    ],
    [
        'name' => 'required',
        'password' => 'required|min:8',
        'email' => 'required|email|unique:users'
    ]
);

Validate form in laravel 5 using routes :-

If you want to validate form on routing process you can done easily with same code apply on routes.php and call function on route making. we need to call a function on post route directly rather sending it to controller method.


Route::post('account/validate', function() {
  // place above controller validate function code here.
}

For more follow laravel 5 form validation

  • Alexandre Hiroshi Muranaka

    How can we change language to the errors messages ?

    • Carlos Hurtado

      You can change language’s errors just copying what language you want from this repository https://github.com/caouecs/Laravel-lang and then you must paste it in “yourProject/resources/lang”.

      After that, in “youProject/config/app.php” you must find the line that says ‘locale’ => ‘en’ and change it by the language you want to use for error messages, for example you must write ‘locale’ => ‘es’ in order to get error messages in Spanish.

      I hope this is helpful to you!