Table of Contents
What happen if you don’t validate your form data in your web application? It will create a bunch of garbage data in database which don’t have specific format and become headache for developer to organize. Non validated form creates a data which is non-unique, doesn’t have specific format like phone number, date etc. To overcome this type of issues, developer should write proper validation rules with appropriate error message and make end user life easy.
In this tutorial, i will show you how to validate form request data in laravel 6. Laravel provides several different approaches to validate your application’s incoming data. By default, Laravel provides a convenient method to validate incoming HTTP request with a variety of powerful validation rules.
Setup Laravel Project
Here i will show you how to validation form data in laravel 6 using customer form example. Let me start by installing fresh laravel.
composer create-project --prefer-dist laravel/laravel laravel-form-validation
Now update database credentials in .env
file
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=laravel-form-validation DB_USERNAME=root DB_PASSWORD=
Now, lets create customer migration using below command.
php artisan make:migration create_customers_table
Above command will create customer migration file under database/migrations directory. Open it and add some fields as shown below.
2019_10_03_164626_create_customers_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateCustomersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('customers', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('firstname'); $table->string('lastname'); $table->string('email'); $table->string('telephone'); $table->date('birthdate'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('customers'); } }
Here i have added firstname
, lastname
, email
, telephone
and birthdate
fields in customer migrations.
Next run php artisan migrate
command to create customers table in database.
Now lets create customer model using below artisan command.
php artisan make:model Customer
Above command will generate Customer.php file under app/ directory. Open it and add $fillable property in it.
# customer.php
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Customer extends Model { /** * The attributes that are mass assignable. * * @var array */ protected $fillable = ['firstname', 'lastname', 'email', 'telephone', 'birthdate']; }
Next, lets create customer controller using below make:controller artisan command.
php artisan make:controller CustomerController
Above command will create CustomerController.php file under app/Http/Controllers directory as shown below.
# CustomerController.php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class CustomerController extends Controller { }
Display Customer Form
To render customer form, lets make create method in CustomerController.php file. create
method will render customer form with help of add.blade.php layout file. Here add.blade.php file contain customer form html code.
# app/Http/Controllers/CustomerController.php class CustomerController extends Controller { /** * Create add customer form */ public function create() { return view('customer.add'); } }
Here is customer form blade file.
# add.blade.php [ Location : resources/views/customer/add.blade.php ]
@extends('layout') @section('content') <div class="title"> <h1>Add Customer</h1> </div> <form action="#" method="POST"> <div class="form-group"> <label for="title">Firstname:</label> <input type="text" class="form-control" id="firstname" name="firstname" value="{{ old('firstname') }}"> </div> <div class="form-group"> <label for="title">Lastname:</label> <input type="text" class="form-control" id="lastname" name="lastname" value="{{ old('lastname') }}"> </div> <div class="form-group"> <label for="title">Email:</label> <input type="text" class="form-control" id="email" name="email" value="{{ old('email') }}"> </div> <div class="form-group"> <label for="title">Telephone:</label> <input type="text" class="form-control" id="telephone" name="telephone" value="{{ old('telephone') }}"> </div> <div class="form-group"> <label for="title">Birth Date:</label> <input type="text" class="form-control" id="birthdate" name="birthdate" value="{{ old('birthdate') }}"> </div> @csrf <button type="submit" class="btn btn-primary">Submit</button> </form> @endsection
Explanation
- add.blace.php file extend layout.blade.php base file to render base layout. Base layout file have bootstrap included so our customer form will render in bootstrap style.
- We will submit form data using POST method type.
- I have added old
{{ old() }}
helper from laravel blade which fill up form value with old data if form validation failed.
To access create
method, Lets define route in web.php file.
# web.php [ Location: routes/web.php ]
<?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('customer.add'); }); Route::get('add-customer', '[email protected]')->name('add_customer');
Lets navigate http://localhost:8000/add-customer
url to render customer form.
Validate Customer Form Data
To validate customer form data, we need to submit customer form data on the server. Let’s make a store
method in CustomerController.php file to validate and store customer form data in database.
CustomerController.php
# app/Http/Controllers/CustomerController.php /** * Create add customer form data */ public function store(Request $request) { $validatedData = $request->validate([ 'firstname' => 'required|max:255', 'lastname' => 'required|max:255', 'email' => 'required|unique:customers|max:50', 'telephone' => 'required', 'birthdate' => 'required' ]); // Store validate data in database }
In the store
method, customer request data will be validate and if data validation become successful then it will store requested data in the database. But if data validation failed then it will redirect to customer form with appropriate validation error message. Here we don’t need any extra blade layout file as failed form validation will redirect to add.blade.php until it become successful.
Lets define a route to access store method, open web.php file and add below route.
# web.php
Route::post('store-customer', '[email protected]')->name('store_customer');
Okay, but as shown in add.blade.php file previously, we haven’t write any code to display validation error message if form validation fails. Lets write some code to display validation error message in customer form blade file.
# add.blade.php
@extends('layout') @section('content') <div class="title"> <h1>Add Customer</h1> </div> @if ($errors->any()) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif <form action="{{ route('store_customer') }}" method="POST" enctype="multipart/form-data"> ...
Here notice that i have added form action url {{ route(‘store_customer’) }} as well. It will submit form data to store
method in CustomerController.php controller file. Now submit the form without filling any form field it will show errors as below.
Change Error Placement
If you need to change validation error placement than you can make it as shown below.
To display separate errors for each field we will check errors object using has method and if any error found, we will display it.
@if ($errors->has('email')) <div class="error">{{ $errors->first('email') }}</div> @endif
Lets add it in customer form blade file as shown below.
# add.blade.php
@extends('layout') @section('content') <div class="title"> <h1>Add Customer</h1> </div> <form action="{{ route('store_customer') }}" method="POST" enctype="multipart/form-data"> <div class="form-group"> <label for="title">Firstname:</label> <input type="text" class="form-control" id="firstname" name="firstname" value="{{ old('firstname') }}"> {{-- Separate error --}} @if ($errors->has('firstname')) <div class="error">{{ $errors->first('firstname') }}</div> @endif </div> <div class="form-group"> <label for="title">Lastname:</label> <input type="text" class="form-control" id="lastname" name="lastname" value="{{ old('lastname') }}"> {{-- Separate error --}} @if ($errors->has('lastname')) <div class="error">{{ $errors->first('lastname') }}</div> @endif </div> <div class="form-group"> <label for="title">Email:</label> <input type="text" class="form-control" id="email" name="email" value="{{ old('email') }}"> {{-- Separate error --}} @if ($errors->has('email')) <div class="error">{{ $errors->first('email') }}</div> @endif </div> <div class="form-group"> <label for="title">Telephone:</label> <input type="text" class="form-control" id="telephone" name="telephone" value="{{ old('telephone') }}"> {{-- Separate error --}} @if ($errors->has('telephone')) <div class="error">{{ $errors->first('telephone') }}</div> @endif </div> <div class="form-group"> <label for="title">Birth Date:</label> <input type="text" class="form-control" id="birthdate" name="birthdate" value="{{ old('birthdate') }}"> {{-- Separate error --}} @if ($errors->has('birthdate')) <div class="error">{{ $errors->first('birthdate') }}</div> @endif </div> @csrf <button type="submit" class="btn btn-primary">Submit</button> </form> @endsection
Above code will render form validation errors as shown below.
Awesome, we just learn about how to validate form data and render/display errors in blade layout file.
Laravel provide lots of validation rules to validate various type form data. You can check available laravel rules here.
In the next tutorial, i will show you how to validate form using Laravel Form Request which is considered best method to validate form data in laravel.
I hope that you may like form validation in laravel 6 tutorial. Please share with your friends, Thank you 🙂