Laravel Form Validation Example Tutorial From Scratch is the topic.
In this tutorial, you will learn to implement validations for various form fields like name, email, phone number, password and confirm password.
Laravel provides very simple way to integrate form validations when you make http calls.
There are also some default rules for validations in laravel framework so that you can directly use them in your laravel web application.
Apart from these default rules, you can also define your custom rules for various filed validations.
I will make one contact form and will implement validations and will also add contact details in MySQL database.
For file validation, read making validation for file uploading in laravel
Checkout the below video for output images.
Now let us make laravel form validation tutorial with example.
Step 1. Fresh project and Database Connection
First of all, fire the below command in your terminal
laravel new laraFormValidation
It will create a fresh new laravel project which will hold the name like “laraFormValidation”
- To connect this laravel project with MySQL database, you need to go to your database administration tool.
- I am using sequel pro but anything else like “phpMyAdmin” is also valid for this tutorial. So create a new database and give it a name like “laraformvalidation“
Now to connect this newly created database with your laravel project, you need to open your .env file in your code editor.
Read the below lines
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=laraformvalidation DB_USERNAME=root DB_PASSWORD=
Fill all the above fields as per your machine configurations.
Once you do this, connection between your database and project is established.
Step 2. Making a new Table
Time to create a new table in our database. For this, trigger the below command in terminal.
php artisan make:migration create_contacts_table
System will create a new migration file after this command.
- You can find this file at app->database->migrations folder. Name of this file would be like “timestamp_create_contacts_table.php“
Code lines for timestamp_create_contacts_table.php will be like below
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateContactsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('contacts', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('name'); $table->string('email'); $table->string('number'); $table->string('password'); $table->string('confirm_password'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('contacts'); } }
Read the up() function in above code.
This functions holds the values which will be the names of the columns of table in our database.
- Column names are id, name, email, number, password and confirm_password
After setting the up() function, run the below command
php artisan migrate
This command will create necessary tables like contacts, migrations, users etc.
We will transact with contacts table in this example.
Step 3. Model and Controller Tasks
Now we will make model and controller classes.
For this, run the below command
php artisan make:controller ContactsController -r -m Contact
This command will try to make a controller file. But for that, a model class is required. We have not created model yet so it will ask you to create model class. Say yes for that.
See the below lines from terminal
php artisan make:controller ContactsController -r -m Contact A App\Contact model does not exist. Do you want to generate it? (yes/no) [yes]: > yes Model created successfully. Controller created successfully.
- Once you say yes and press enter, system will create one controller and one model class.
Name of controller will be ContactsController.php and for model, it should be “Contact.php”
Now open up app->Contact.php and code block should be like below
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Contact extends Model { // public $table = "contacts"; }
I have initialize $table in this class. No need to do anything else in this class.
Now navigate towards app->Http->Controllers->ContactsController.php file.
Source snippet for ContactsController.php is like the following
<?php namespace App\Http\Controllers; use App\Contact; use Illuminate\Http\Request; class ContactsController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { //dd('here'); return view('contact'); } public function storeContact(Request $request) { $this->validate($request,[ 'name' => 'required|min:5|max:35', 'email' => 'required|email|unique:contacts', 'number' => 'required|numeric', 'password' => 'required|min:3|max:15', 'confirm_password' => 'required|min:3|max:15|same:password', ],[ 'name.required' => ' The first name field is required.', 'name.min' => ' The first name must be at least 5 characters.', 'name.max' => ' The first name may not be greater than 35 characters.', 'email.unique' => ' This Email ID already exists ! Try another', ]); $contact = new Contact(); $contact->name = request('name'); $contact->email = request('email'); $contact->number = request('number'); $contact->password = request('password'); $contact->confirm_password = request('confirm_password'); $contact->save(); //return view('uploadfile'); return back()->with('success', 'Contact added Successfully With Validation'); } /** * 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 \App\Contact $contact * @return \Illuminate\Http\Response */ public function show(Contact $contact) { // } /** * Show the form for editing the specified resource. * * @param \App\Contact $contact * @return \Illuminate\Http\Response */ public function edit(Contact $contact) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Contact $contact * @return \Illuminate\Http\Response */ public function update(Request $request, Contact $contact) { // } /** * Remove the specified resource from storage. * * @param \App\Contact $contact * @return \Illuminate\Http\Response */ public function destroy(Contact $contact) { // } }
Above code includes some functions which are pre written by the compiler. We do not need to touch them.
- I have created two functions manually. One is index() and another is storeContact(). I will explain both these functions in details but later on.
Step 4. Making Routes For Validation
Go to your app->web.php file and write down the below code lines
<?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('welcome'); }); Route::get('contact','ContactsController@index'); Route::post('addcontact','ContactsController@storeContact');
- I have added two routes manually. Other things are written by compiler.
- First one is GET request to the /contact . This route will access the index() function from the ContactsController.php file.
- Second one /addcontact will make POST request and will call storeContact() from the ContactsController.php file.
Below is the code lines for index() function
public function index() { //dd('here'); return view('contact'); }
- When you hit http://127.0.0.1:8000/contact in browser, system will call above code.
It will simply try to open the contact.blade.php file.
Let us create contact.blade.php file.
Step 5. Making Blade Views
Make a new file called contact.blade.php inside resources->views directory.
Below is the code snippet for contact.blade.php file.
<!DOCTYPE html> <html> <head> <title>File Uploading in Laravel</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" /> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <br /> <div class="container"> <h3 >Form Validation Laravel</h3> <br /> @if (count($errors) > 0) <div class="alert alert-danger"> Upload Validation Error<br><br> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif @if ($message = Session::get('success')) <div class="alert alert-success alert-block"> <button type="button" class="close" data-dismiss="alert">×</button> <strong>{{ $message }}</strong> </div> @endif <form method="POST" action="/addcontact" enctype="multipart/form-data"> @csrf <div class="form-group"> <label class="lable" for="name"> Name </label> <div class="control"> <input type="text" class="form-control" name="name" placeholder="Name" value="" required> </div> </div> <div class="form-group"> <label class="lable" for="name"> Email </label> <div class="control"> <input type="text" class="form-control" name="email" placeholder="Email" value="" required> </div> </div> <div class="form-group"> <label class="lable" for="name"> Number </label> <div class="control"> <input type="text" class="form-control" name="number" placeholder="Number" value="" required> </div> </div> <div class="form-group"> <label class="lable" for="name"> Password </label> <div class="control"> <input type="password" class="form-control" name="password" placeholder="Password" value="" required> </div> </div> <div class="form-group"> <label class="lable" for="name"> Confirm Password </label> <div class="control"> <input type="password" class="form-control" name="confirm_password" placeholder="Confirm Password" value="" required> </div> </div> <div class="form-group"> <div class="control"> <button type="submit" class="btn btn-primary">Add Contact</button> </div> </div> </form> </body> </html>
- This file will create a form with some input fields and one button as you have seen in the output video.
- User needs to enter name, email, password, number etc. in the input fields.
If all the validations are satisfied then system will insert the contact details in the database otherwise it will print the error message inside red rectangle.
Below code in printing the error messages.
@if (count($errors) > 0) <div class="alert alert-danger"> Upload Validation Error<br><br> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif
- foreach loop will have the number of iterations equals to the number of errors.
If system have successfully added the record into the MySQL database then below code will print the success message in green rectangle.
@if ($message = Session::get('success')) <div class="alert alert-success alert-block"> <button type="button" class="close" data-dismiss="alert">×</button> <strong>{{ $message }}</strong> </div> @endif
- When the user clicks the Add Contact Button, compiler will run the storeContact() from the ContactsController.php file.
Below is the code for storeContact() function.
public function storeContact(Request $request) { $this->validate($request,[ 'name' => 'required|min:5|max:35', 'email' => 'required|email|unique:contacts', 'number' => 'required|numeric', 'password' => 'required|min:3|max:15', 'confirm_password' => 'required|min:3|max:15|same:password', ],[ 'name.required' => ' The first name field is required.', 'name.min' => ' The first name must be at least 5 characters.', 'name.max' => ' The first name may not be greater than 35 characters.', 'email.unique' => ' This Email ID already exists ! Try another', ]); $contact = new Contact(); $contact->name = request('name'); $contact->email = request('email'); $contact->number = request('number'); $contact->password = request('password'); $contact->confirm_password = request('confirm_password'); $contact->save(); //return view('uploadfile'); return back()->with('success', 'Contact added Successfully With Validation'); }
Making Validation Rules
Consider the below coding lines
$this->validate($request,[ 'name' => 'required|min:5|max:35', 'email' => 'required|email|unique:contacts', 'number' => 'required|numeric', 'password' => 'required|min:3|max:15', 'confirm_password' => 'required|min:3|max:15|same:password',
- These lines defining all the validations like required, minimum and maximum number of characters, email type etc.
- Array includes all the fields like name, email, number etc. so that it becomes easy to define specific validations to specific fields.
Generally, laravel system have pre defined error messages for almost every validation. But the beauty is that we can customize these error messages.
Now for all the validations, we can define the custom error message with the help of below source snippet.
[ 'name.required' => ' The first name field is required.', 'name.min' => ' The first name must be at least 5 characters.', 'name.max' => ' The first name may not be greater than 35 characters.', 'email.unique' => ' This Email ID already exists ! Try another', ]);
Now if all the validations are satisfied then compiler will run the below lines
$contact = new Contact(); $contact->name = request('name'); $contact->email = request('email'); $contact->number = request('number'); $contact->password = request('password'); $contact->confirm_password = request('confirm_password'); $contact->save(); //return view('uploadfile'); return back()->with('success', 'Contact added Successfully With Validation');
- Above snippet will simply fetch the values entered by user and will insert them into the database. (In contacts table)
You can also customize success message using the last line.