Validation in Laravel with Example

Validation in Laravel


Laravel Validation is the way through which we can verify and filter the data coming to the Application database. We can have clean and validated data in the database coming with HTTP with powerful validation rule.

As we know that we store the data in the Database using form. As we must not fill our database with junk and invalid data, we do form validation in client Side as well as server side. The validation in laravel purpose is to get the exact data what is required for application.

Route::get('personal-detail/show', 'PersonalController@showForm');
Route::post('personal-detail/save', 'PersonalController@savePersonalData');

Above two route, One route purpose is to show the Personal Detail form other is to save the personal data in the database. While saving the blog data we will validate all the data format and blog post then we will store in database.

Personal Form Code is below:

<body>
<div class="container" style="width:80%; margin-left:10%;margin-right:10%">
  <h2>Validation form</h2><br/>
  
   {!! Form::open(['url'=>'form-validation/save','id'=>'savePostMaster', 'class' => 'formstyle']) !!}
    <div class="form-group">
      <label for="fullname">Full Name:</label>
      {!! Form::text('FULL_NAME','',array('class'=>'form-control ','id'=>'FULL_NAME','placeholder'=>'Enter Your Full Name')) !!}
      <span class="error" style="color:red"> @if($errors->has('FULL_NAME')) {{ $errors->first('FULL_NAME') }} @endif</span>
    </div>
    <div class="form-group">
      <label for="mobile">Mobile Number:</label>
      {!! Form::text('mobile','',array('class'=>'form-control','id'=>'mobilr','placeholder'=>'Enter Mobile Number')) !!}
      <span class="error" style="color:red"> @if($errors->has('mobile')) {{ $errors->first('mobile') }} @endif</span>
    </div>
    <div class="form-group">
      <label for="email">Email:</label>
      {!! Form::email('email','',array('class'=>'form-control','id'=>'email','placeholder'=>'Enter Email ID')) !!}
      <span class="error" style="color:red"> @if($errors->has('email')) {{ $errors->first('email') }} @endif</span>     
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
  {!!form::close()!!}
</div>

</body>

 O/P of above code.

laravel form validation

We use laravel Validate function to implement the validation rules in the controller, if the validation method fails then it will halt the execution of code further and it will redirect to the form with error message. We will write the validation logic in PersonalController.

Below is the validation code for your reference purpose.

Validation in Laravel Example


public function saveFormVal(Request $request){         $input = Input::all();         // Validation Code Starts Here         $validatedData = $request->validate([             'FULL_NAME' => 'required|max:25',             'mobile' => 'required|digits:10|unique:valid_table,mobile',             'email' => 'required|email|max:255',         ]);              }

If You will see the above validation code we have applied various validation rules to filter the input Data coming through the HTTP Request. Input field named with FULL_NAME, mobile, email all have certain condition. Like these input field can't be NULL, the mobile number cant be duplicate as well as it must have 10 digit and email id format must be maintain.

If any Input field will not satisfy the condition then validation will fail and it will redirect back with validation error message. See the below image for your reference.

Validation Error message
Refer the input field, User tried to insert the mobile number which have 9 digit as well as the email Id format is not maintain. so these data is junk data which don't serve the purpose.

Here Validation comes in picture, It will filter this all type of unwanted data and will not allow them to store in the database.  


To show all the error on the view add below code.

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

This above code will print all the validation error message in list format. Above Image is the example which you can refer.

If you want to print all the validation message below the respective input field then you must specify with validation first() method. Below code is there for your reference.

{!! Form::open(['url'=>'form-validation/save','id'=>'savePostMaster', 'class' => 'formstyle']) !!}
    
   <div class="form-group">
      <label for="fullname">Full Name:</label>
      {!! Form::text('FULL_NAME','',array('class'=>'form-control ','id'=>'FULL_NAME','placeholder'=>'Enter Your Full Name')) !!}
      <span class="error" style="color:red"> @if($errors->has('FULL_NAME')) {{ $errors->first('FULL_NAME') }} @endif</span>
    </div>

    <div class="form-group">
      <label for="mobile">Mobile Number:</label>
      {!! Form::text('mobile','',array('class'=>'form-control','id'=>'mobilr','placeholder'=>'Enter Mobile Number')) !!}
      <span class="error" style="color:red"> @if($errors->has('mobile')) {{ $errors->first('mobile') }} @endif</span>
    </div>

    <div class="form-group">
      <label for="email">Email:</label>
      {!! Form::email('email','',array('class'=>'form-control','id'=>'email','placeholder'=>'Enter Email ID')) !!}
      <span class="error" style="color:red"> @if($errors->has('email')) {{ $errors->first('email') }} @endif</span>     
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>

  {!!form::close()!!}

In the above code we have specify the validation error code for each input field which will highlight the error if any validation fails. Below is the image for your reference.

Laravel Validation Error
If any input field will not meet the validation requirement then the Error message will be shown below the Input field.










Some validation Rule list which you can apply on the input filed to get the exact user data to serve our purpose.

Laravel Validation Rules


Validation Rule
Purpose
required
Required validation will ensure that input field must not be null.
alpha
Alpha will ensure that input field must have only Alphabetic Character
Alpha_num
Alpha_nun will check that input field will have only alphabet and Numeric as a input.
digits:value
Digits will ensure that the input filed data must have only numeric data with exact digit length.
digits_between:min,max
Digits_between will check that the input data coming through HTTP request must have numeric data only as well as it must contain the digit in between the specified length.
email:value
Email validation rule will check and ensure that proper email format is given which is followed worldwide.
image
Image will ensure that the uploaded file in the form must be in valid image format. Like JPG, PNG, JPEG, SVG, BMP, GIF etc.
integer
This will ensure that input data will have only integer value only.
ip
This will ensure that the entered value for input field must have in IP Format.
min:value
Min validate that the input field data must have minimum digit.
max:value
Max validation rule ensure that input field must not have greater than the specified digit.
not_regex:pattern
This will ensure that the given data must match with given regular expression.
required_if:anotherfield,value,...
This will check based on the other input field. If first input value is there then the next input field is required.
unique:table,column
This will ensure that the entered data must not have the duplicate value in the specified table column.

Validation Code and Rules Example below with Example and Explanation.


'password' => 'required|min:8|confirmed',
'password_confirmation' => 'required',

'PICK_TEXT'=>'required|max:200',

'code'=> 'required|unique:educational_district,code|digits:3',

'STORE_INDEX_SEQUENCE'=>'required|integer',

'file' => 'required|max:204800|mimes:pdf',

'nadid'=>'required|min:9|max:12|unique:ENTRACNEDOCUMENTMST,
DOCUMENTNUMBER,'.Input::get('id').'|confirmed|
regex:/^[A-Z][A-Z0-9.,$;]+$/',

'nadid_confirmation'=>'required|min:9|max:12',

'sms_email' => 'required|not_in:0',                   
'senderid'=>'required_if:sms_email,==,1',
'email_from'=>'required_if:sms_email,==,2',

'status' => 'required',
'remarks' => 'required_if:status,==,0,2,3,5',

'approved_status' => 'required',
'capacity_applied' => 'required|integer',
'capacity_approved' => 'required_if:approved_status,==,1|integer|
lte:capacity_applied',

'remarks' => 'required_if:approved_status,==,0,2,3',

'image' => 'required:max:204800|mimes:jpeg,jpg,bmp,pdf,png'

'class_id' => 'required|not_in:0',

'code'=> 'required|unique:mp_constituencies,code,'.$mp_constituency->id.',id',

'mobile_no'     => 'required|integer|digits:10',

Using Eloquent in Validation 

'email' => 'unique:App\User,email_address'

Create Validators Manually 


If we don't want to use validate() method, then we can create validators manually using validation Facades.We use make() method to create manual validator.
   
use Illuminate\Support\Facades\Validator;

 $validator = Validator::make($request->all(), [
            'first_name' => 'required|max:255',
            'mobile' => 'required|digits:10',
        ]);

        if ($validator->fails()) {
            return redirect('/personal-details')
                        ->withErrors($validator)
                        ->withInput();
        }


Instead of writing url redirection validation code once the validation fails, you can use auto url redirection using validate method. You have to call the instance.

$validator = Validator::make($request->all(), [
            'first_name' => 'required|max:255',
            'mobile' => 'required|digits:10',
        ])->validate();



Laravel Validation Form Example :


<div style="background-color:white">
  <h2>Laravel Form Validation Example</h2>
  <form method="POST" action="/form-validation" autocomplete="off">
    @if(count($errors))
      <div class="alert alert-danger">
        <strong>Whoops!</strong> There were some problems with your input.
        <br/>
        <ul>
          @foreach($errors->all() as $error)
          <li>{{ $error }}</li>
          @endforeach
        </ul>
      </div>
    @endif
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
    <div class="row">
      <div class="col-md-12">
        <div class="form-group {{ $errors->has('firstname') ? 'has-error' : '' }}">
          <label for="firstname">Full Name:</label>
          <input type="text" id="fullname" name="fullname" class="form-control" placeholder="Enter Full Name" value="{{ old('firstname') }}">
          <span class="text-danger">{{ $errors->first('fullname') }}</span>
        </div>
      </div>
    </div>
    <div class="row">
      <div class="col-md-12">
        <div class="form-group {{ $errors->has('emailid') ? 'has-error' : '' }}">
          <label for="emailid">Email ID:</label>
          <input type="text" id="emailid" name="emailid" class="form-control" placeholder="Enter Email ID" value="{{ old('emailid') }}">
          <span class="text-danger">{{ $errors->first('emailid') }}</span>
        </div>
      </div>
    </div>
    <div class="row">
      <div class="col-md-12">
        <div class="form-group {{ $errors->has('mobileno') ? 'has-error' : '' }}">
          <label for="mobileno">Mobile No:</label>
          <input type="text" id="mobileno" name="mobileno" class="form-control" placeholder="Enter Mobile No" value="{{ old('mobileno') }}">
          <span class="text-danger">{{ $errors->first('mobileno') }}</span>
        </div>
      </div>
    </div>
    <div class="row">
      <div class="col-md-6">
        <div class="form-group {{ $errors->has('password') ? 'has-error' : '' }}">
          <label for="password">Password:</label>
          <input type="password" id="password" name="password" class="form-control" placeholder="Enter Password" >
          <span class="text-danger">{{ $errors->first('password') }}</span>
        </div>
      </div>
      <div class="col-md-6">
        <div class="form-group {{ $errors->has('confirmpassword') ? 'has-error' : '' }}">
          <label for="confirmpassword">Confirm Password:</label>
          <input type="password" id="confirmpassword" name="confirmpassword" class="form-control" placeholder="Enter Confirm Passowrd">
          <span class="text-danger">{{ $errors->first('confirmpassword') }}</span>
        </div>
      </div>
    </div>
    <div class="form-group">
      <button class="btn btn-success">Submit</button>
    </div>
  </form>
</div>



100 Top Interview Laravel Question for Fresher and Experience

 

100 Laravel Framework Interview Question


1) Describe Laravel?

 Laravel is MVC(Model View Controller) architecture based open Source php Framework developed by Taylor Otwell. Latest version of Laravel Framework is 7.0 which got released on March 3rd.

Laravel 1st version got released on 9th June 2011.



2) What are the Laravel Framework Feature ?

 Top Feature of laravel Framework is below.

  • CRSF (cross-site request forgery )
  • Eloquent ORM
  • Laravel paginations
  • Database Seeding
  • Reverse Routing
  • Query builder
  • Route caching
  • Database Migration
  • Unit Testing
  • IOC (Inverse of Control) Container.
  • Job middleware
  • Lazy collections



3) Define Laravel Eloquent ORM ?

Laravel Eloquent feature is object Oriented paradigm approach of database communication. In Eloquent we create Model for each Table in the database, which set the communication (Fetching, Inserting, Deleting, Modifying the Record ) with database. It represent Database Table as a Class.



Laravel Eloquent ORM With Example Read More






4) What is Soft Delete? How to use it in Laravel Model?

Soft Delete is feature of laravel framework which helps when model is soft deleted. In this scenario the data record is not deleted form the database table instead deleted_at timestamp is maintained.




5) Define Laravel Query Builder ?

Query Builder in Larevel is a Package through which we create and run database query Quickly to run the application smoothly. Query Bulider Use PHP Data Object (PDO) where we dont have to worry about the SQL Injection. It can perform all Database Operation such as CRUD, DB Connection, Aggregate Function etc.



Laravel Query Builder With Example Read More






6) Explain Middleware Concept in Laravel?

Laravel Middleware provide a filter as well as it act as interface or Middle-Man between HTTP request and response which access the application. Middleware is a way to filter all the bad or Forgery request which try to access your Application.

Laravel Middleware Type 
  • Global Middleware 
  • Route Middleware


Laravel Middleware With Example Read More






7) Define Aggregate Function ? What are the aggregate function available in Lravel Query Builder?

In Aggregate Function, Database Table Rows are grouped together based on certain Criteria to get specific summary value. Laravel Provide various aggregate function which we can use in our query, list is below for your reference.
  • count() function
  • max() function
  • min() function
  • sum() function
  • avg() function
Note: All Aggregate function defined above ignore NULL Value except Count() function.



8) Explain Laravel Migration? Write the Artisan Command for Laravel Migration ?

Laravel Database Migration is way through which we build and maintain the Database Schema. Migration is Version Control of Your DB, which will allow Developer team easily to modify and share the DB Schema.

Laravel DB Migration provide the facility for those who is not able and poor in maintaining, updating Database.

Migration In Laravel contain by default Two method up() method is called when a DB is modified or changed. Whereas, the DB Migration down() method is called when DB is reverted back.


Artisan Command for Laravel migration.    php artisan migrate



9) Describe Laravel Reverse Routing ?

Laravel reverse Routing is one of the Awesome Route Feature. Reverse Routing is process of generating the URL based on the Route Deceleration. Reverse Routing sets a relationship between links and web routes.

Consider below route declared as Example (consider your Website as www.abc.com)

Route::get('user-login','UserController@userLogin');

{ { url( '/usre-login' ) } }

$url-link = URL::route('usre-login');

$redirect
-link = Redirect::route('usre-login');

Above three will generate the URL which is below as a example :

URL : www.abc.com/user-login

Now reverse routing is process to generate the url based on Name or other parameter.

  {{ HTML :: link_to_action( ' UserController@userLogin ' ) }}  

This above reverse routing will also generate or point the same URL www.abc.com/user-login .

 
10) What is Artisan ? List some Common Php Artisan command?

 Artisan is command line Interface tool which help in laravel Application Building. To Kmow all this List of Artisan command, Use the below Artisan command.

php artisan list

 List of Common Artisan Command for hassle free Laravel application Development is below:-
  • php artisan list
  • php artisan make:controller controller-name
  • php artisan make:model model-name  
  • php artisan migrate
  • php artisan make:middleware middleware-name  
  • php artisan tinker


11) Define Controller ?

Controller handle all the HTTP Request logically and divert the Web Traffic to View and Model. It Contain all the Http Handling Logic within Single Class. Artisan Command to create the Controller is below for your Reference.

php artisan make:controller controllerName

Controller is C of  MVC(Model View Controller).


12) List out some Laravel Official Packages?

Laravel Packages list is below for your reference.
  • Dusk Package
  • Envoy Package
  • Horizon Package
  • Cashier Package
  • Passport Package
  • Scout Package
  • Socialite Package
  • Telescope Package
 

13) What is the difference between find() and where() method in laravel?

The Major Difference between them is find() method always use Primary Key to filter the table record, whereas where() method uses any table column to filter the table record set.

find() method will return the single table row from the database. where() method return multiple record based on the condition.



14) What is Named Route in Laravel ?

Named Route is a friendly name given to the route the reference. We can use Named rout to specify the particular Route as well as to generate the URL / to redirect to specific URL.

Route::post('profile-data/save', 'ProfileController@saveProfile')->name('profileData');

You must keep the route name always unique. Generating / Redirecting Url for Names Route is below for your reference.

$url = route('profile');
return redirect()->route('profile');

With Name Route we can pass the second or third parameter as a argument.

Route::post('profile-data/{id}', 'ProfileController@updateProfile')->name('profileData');

To pass the parameter as argument in the named Route code is below for your reference.

$url = route('profile', ['id'=>1 ]);

If we pass the additional parameter in the array, that will be automatically added in the URL generated query String. Below is the example for reference.

$url = route('profile-data/{id}', ['id' => 1, 'rollno' => '1004']);
URL String generated is below /1/profile?rollno=1004



15) Define Laravel Validation?

Laravel Validation is the way through which we can verify and filter the data coming to the Application database. We can have clean and validated data in the database coming with HTTP with powerful validation rule.

As we know that we store the data in the Database using form. As we must not fill our database with junk and invalid data, we do form validation in client Side as well as server side. The validation purpose is to get the exact data what is required for application.

You can use validate method for data filteration.

$validatedData = $request->validate([
            'FULL_NAME' => 'required|max:25',
            'mobile' => 'required|digits:10|unique:valid_table,mobile',
            'email' => 'required|email|max:255',
        ]);

You can use Validation make() method to create manual validator.

$validator = Validator::make($request->all(), [
            'first_name' => 'required|max:255',
            'mobile' => 'required|digits:10',
        ])->validate();



16) Define Route::fallback method with Example?

Route::fallback method is another feature of  Laravel Routing in which we handle the HTTP request which do not match with our route list. By default laravel render the 404 not found page using exception handler. Now laravel fallback method you can define and redirect to the view which will get execute if not HTTP request matches.

You must always define the Route::fallback method at the last of route file. Below is the code for your reference.

Route::fallback(function() {
    return 'You have landed on wrong url. ';
});




Our Feature Post

There is a tree between houses of A and B If the tree leans on As House

    There is a tree between houses of A and B. If the tree There is a tree between houses of A and B. If the tree leans on A’s House, the t...

Our Popular Post