Table of contents
1.
Introduction
2.
What is Laravel Validation
3.
Available Validation Rules in Laravel
4.
Creating a Basic Laravel Project
4.1.
Adding Validation
4.1.1.
Validation 1
4.1.2.
Validation 2
5.
Frequently Asked Questions
5.1.
What is PHP?
5.2.
What is MVC?
5.3.
What is a framework?
5.4.
What is Laravel?
5.5.
What is Laravel Validation?
6.
Conclusion
Last Updated: Mar 27, 2024
Medium

Laravel Validation

Author Rajat Agrawal
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

As we know, PHP is the most popular scripting language for Web development. There are different frameworks based on PHP in the market. Laravel is one of the open-source PHP frameworks. It uses an MVC structure to develop the application using PHP and provides many functionalities for easier development of web applications.

laravel validation

In this blog, we will learn about Laravel Validation which is used to validate incoming data and checks its authenticity.

Recommended Topic, Interpolation in Angular

Recommended Topic, Cognizant Eligibility Criteria

What is Laravel Validation

Validation is the process of checking the data coming from the user. This will help the user to submit the correct data and prevent them from submitting any incorrect data. 

In Laravel, some predefined Validation Rules are used in the laravel application to validate the user’s data.

Some of the available Validation Rules in laravel are:-

  • Accepted
     
  • Required
     
  • Confirmed
     
  • Max
     
  • Min
     

Let’s understand how laravel validation works by creating a basic laravel project.

Available Validation Rules in Laravel

Laravel provides a wide range of validation rules to validate the input entered by the user. Below are the most used validation rules available in laravel.

Sr. No.

Validation Rules

Description

1 Accepted The field must be “yes”, “on”, “true”, or 1.
2 Required It is the mandatory field for input data.
3 Confirmed The field must have a matching field of {field}_confirmation.
4 Max The field must have a maximum value.
5 Min The field must have a minimum value.
6 Regular Expression The field must match the given regular expression.
7 Size The field must have a size the same as the given value.
8 numeric The field must be a numeric value.
9 string The field must be a string.
10 integer The field must be an integer.
11 url The field must be a valid URL.
12 email The field must be a valid email address.
13 date The field must be a valid date.
14 nullable The field must be null.
15 password The field must match the authenticated user’s password.

Creating a Basic Laravel Project

We will create a laravel project to understand how validation works in laravel. 
Let’s create the project step by step.

Step 1: First of all, we will create a laravel project named codingninjas. To create this project, run the following command in the xampp/htdocs directory.

composer create-project laravel/laravel codingninjas
You can also try this code with Online PHP Compiler
Run Code


After running the command, the codingninjas project has successfully been created in the xampp/htdocs directory. 

basic laravel project


Step 2: After creating the project, we will create a model named Subject with the database migration.

To create the Subject model, run the following command.

php artisan make:model Subject -m 
You can also try this code with Online PHP Compiler
Run Code

 

After running the above command, a Subject model will be created in the app/Models folder, and migration will be created in the config/migrations folder.

Subject Model

The Subject.php file contains the following code.

 <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Subject extends Model {
	use HasFactory;
}
You can also try this code with Online PHP Compiler
Run Code


And the 2022_11_19_111650_create_subjects_table.php file contains the following code.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration {
	/**
	* Run the migrations.
	*
	* @return void
	*/
	public function up() {
		Schema::create('subjects', function (Blueprint $table) {
			$table->id();
			$table->timestamps();
		});
	}

	/**
	* Reverse the migrations.
	*
	* @return void
	*/
	public function down() {
		Schema::dropIfExists('subjects');
	}
};
You can also try this code with Online PHP Compiler
Run Code


Step 3: Now, we will create a controller that handles all the database operations.

To create the SubjectController, run the following command:

php artisan make:controller SubjectController --resource 
You can also try this code with Online PHP Compiler
Run Code


After running the above command, the SubjectController will be created successfully.

SubjectController

The SubjectController.php file contains the following code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class SubjectController extends Controller {
	/**
	* Display a listing of the resource.
	*
	* @return \Illuminate\Http\Response
	*/
	public function index(){
	}

	/**
	* Show the form for creating a new resource.
	*
	* @return \Illuminate\Http\Response
	*/
	public function create(){
	}

	/**
	* Store a newly created resource in storage.
	*
	* @param  \Illuminate\Http\Request  $request
	* @return \Illuminate\Http\Response
	*/
	public function store(Request $request){
	}

	/**
	* Display the specified resource.
	*
	* @param  int  $id
	* @return \Illuminate\Http\Response
	*/
	public function show($id){
	}

	/**
	* Show the form for editing the specified resource.
	*
	* @param  int  $id
	* @return \Illuminate\Http\Response
	*/
	public function edit($id){
	}

	/**
	* Update the specified resource in storage.
	*
	* @param  \Illuminate\Http\Request  $request
	* @param  int  $id
	* @return \Illuminate\Http\Response
	*/
	public function update(Request $request, $id){
	}

	/**
	* Remove the specified resource from storage.
	*
	* @param  int  $id
	* @return \Illuminate\Http\Response
	*/
	public function destroy($id){
	}
}
You can also try this code with Online PHP Compiler
Run Code


Step 4: After creating the controller, we need to create a route for all the methods of the controller. 

To create a route, we need to write the following code in the web.php file. 

Route::resource('subject','SubjectController');
You can also try this code with Online PHP Compiler
Run Code


Step 5: Now, we will define the index( ) method of the SubjectController class. The code for the index( ) method is the following:

public function index()   {  
	$subject=Subject::all();  
	return view('index',compact('subject'));  
}  
You can also try this code with Online PHP Compiler
Run Code


Step 6: Now, we will create a view page for our project. The name of the page is index.blade.php

@extends('layout.master')  
@section('content')  
<h1> Subject </h1>  
<form action=="{{ route('subject.store') }}"  method="Post">  
	@csrf  
	<div><input type="text" name="name"></div>  
	<br/>  
	<div><input type="button" value="Add New Subjects"> </div>  
	</form>  
	<ul>  
	@foreach($subject as $subjects)  
	<li>{{$subjects->name}}</li>  
	@endforeach  
	<ul>  
@endsection  
You can also try this code with Online PHP Compiler
Run Code


Output:

output

Step 7: To save the subject names in the database upon clicking on the Add New Subjects button, we have to modify the store( ) method of the SubjectController class. 

The code for the store( ) method is the following:

public function store(Request $request) { 
	// validating the name field. 
	$data=$request->validate([    
		'name'=>'required']);  
	$subject=new Subject;  
	$subject->name=$request->get('name');  
	$subject->save();  
}  
You can also try this code with Online PHP Compiler
Run Code


As we have successfully created a laravel project, we can now put different validations on this project.

Adding Validation

Validation 1

When the name field is empty, and the user clicks on the Add New Subject button. In this case, we need to put validation and show some error message to the user.

In order to show the error message, Laravel provides an error variable, which displays the error message. It can be used as follows:-

{{$errors->first('name')}}  
You can also try this code with Online PHP Compiler
Run Code


Put the error message in the index.blade.php; the new code will look like this:

@extends('layout.master')  
@section('content')  
<h1> Subject </h1>  
<form action=="{{ route('subject.store') }}"  method="Post">  
	@csrf  
	<div><input type="text" name="name"></div>  
	<br/>   
	<div>{{$errors->first('name')}}</div>  
	<br/>  
	<div><input type="button" value="Add New Subjects"> </div>  
	</form>  
	<ul>  
	@foreach($subject as $subjects)  
	<li>{{$subjects->name}}</li>  
	@endforeach  
	<ul>  
@endsection  
You can also try this code with Online PHP Compiler
Run Code


Output: 

output

Validation 2

When you want to restrict the character length in the textbox. Let’s say we want at least 6 characters in the name field. To achieve this, we can use the min field.

 public function store(Request $request) {  
 	// validating the name field. 
	$data=$request->validate([    
		'name'=>'required|min:6']);  
	$subject=new Subject;  
	$subject->name=$request->get('name');  
	$subject->save();  
} 
You can also try this code with Online PHP Compiler
Run Code


Output:

output

This is how we put different validations in the laravel project.

Frequently Asked Questions

What is PHP?

PHP stands for Hypertext Preprocessor. It is the most popular and widely used scripting language for creating web applications. 

What is MVC?

MVC stands for Model-View-Controller. It is the way to layout any web project. The model is for the database, the view is for static files, and the controller is used as an interface between the model and the view. 

What is a framework?

A framework is a set of tools in programming on which to build well-structured, reliable software and systems.

What is Laravel?

Laravel is one of the open-source PHP frameworks. It uses an MVC structure to develop the application using PHP and provides many functionalities for easier development of web applications.

What is Laravel Validation?

Laravel Validation is the process of checking the data coming from the user. This will help the user to submit the correct data and prevent them from submitting any incorrect data. 

Conclusion

In this article, we have extensively discussed Laravel Validation, why we need validation, and the different validation rules provided by Laravel. I hope you enjoyed this blog on Laravel Validation.

Recommended Readings:

Also, check out these exciting courses from coding ninjas to expand your knowledge, Coding CourseCode StudioInterview ExperienceGuided PathInterview ProblemsTest SeriesLibrary, and Resources

Happy Coding!

Live masterclass