Form Validation In Laravel 8 

in any website, we can see different type of forms validation available . we need to validate forms because it will create a bunch of garbage data in database. if we will specify which type of data we require so it will store proper data in database table. we need to overcome garbage data to apply validation on forms. in this post I will show you how to apply forms validation in laravel 8.

Table of Contents

Create migration for customers

Customer Form(controller, view, model, route)

Validate Customer Form

Error show

Create migration for customers

firstly, we need to create new customers migration with below command –

php artisan make:migration create_customers_table

 above command will create customer migration. migration file will available under database/migrations directory. open it and add some fields as shown below.

2023_01_19_123154_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('telephone');
            $table->string('emailid');            
            $table->tinyInteger('is_active')->default(1);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('customers');
    }
}

after that changes, we need to run migrate command. here I have added firstname, lastname, telephone, emailid and is_active fields column in table.

php artisan migrate

Customer Form(controller, view, model, route)

Now, I will create controller for customer with below command.

php artisan make:controller CustomerController

I have open controller file and added below code. customer controller created in app\Http\Controllers directory.

CustomerController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class CustomerController extends Controller
{
     /**
     * Create add customer add form
     */
    public function create() {
        return view('customer.add');
    }
}

after that, I will create new view file under resources\views\customer add.blade.php .

add.blade.php

@extends('layouts.app')
@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">

<div class="title">
  <h1>Add New Customer</h1>
</div>
<form action="{{ route('customer.store') }}" method="POST">
  @csrf
  <div class="form-group">
    <label for="title">First name:</label>
    <input type="text" class="form-control" id="firstname" name="firstname" value="{{ old('firstname') }}">
    @if ($errors->has('firstname'))
   <div class="error">{{ $errors->first('firstname') }}</div>
@endif
  </div>
  <div class="form-group">
    <label for="title">Last name:</label>
    <input type="text" class="form-control" id="lastname" name="lastname" value="{{ old('lastname') }}">
    @if ($errors->has('lastname'))
   <div class="error">{{ $errors->first('lastname') }}</div>
@endif
  </div>
  <div class="form-group">
    <label for="title">Telephone No:</label>
    <input type="text" class="form-control" id="telephone" name="telephone" value="{{ old('telephone') }}">
     @if ($errors->has('telephone'))
   <div class="error">{{ $errors->first('telephone') }}</div>
@endif
  </div>
  <div class="form-group">
    <label for="title">Email Id:</label>
    <input type="text" class="form-control" id="emailid" name="emailid" value="{{ old('emailid') }}">
     @if ($errors->has('emailid'))
   <div class="error">{{ $errors->first('emailid') }}</div>
@endif
  </div>
  <button type="submit" class="btn btn-primary">Create</button>
</form>
</div>
</div>
</div>
</div>
@endsection

now, I will create new model for customer.

php artisan make:model Customer

app\Models\Customer.php

<?php

namespace App\Models;

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

class Customer extends Model
{
    use HasFactory;
    protected $fillable = ['firstname', 'lastname', 'telephone','emailid',  'is_active'];
}

we need to add model in customer controller in top.

use App\Models\Customer;

Validate Customer Form

now, updated customercontroller.php file.

<?php

namespace App\Http\Controllers;
use App\Models\Customer;
use Illuminate\Http\Request;
use Validator;
class CustomerController extends Controller
{
     /**
     * Create add customer add form
     */
    public function create() {
        return view('customer.add');
    }
    public function store(Request $request) {
    	$data = $request->all();
        $rules = [
            'firstname' => 'required',
            'lastname' => 'required',
            'telephone' => 'required',
            'emailid'=> 'required|email'
        ];

        $validator = Validator::make($data, $rules);
    
        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
         }
          
        $customer_data=array('firstname'=>$request->firstname,
     	                  'lastname'=>$request->lastname,
     	                  'telephone'=>$request->telephone,
     	                  'emailid'=>$request->emailid,
     	                  'is_active'=>true);
       Customer::create($customer_data);
       return redirect()->route('customer.create')
                        ->with('success','Customer successfully created.');

    }
    
}

we need to create new route for customer. here open route file routes/web.php .

web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\CustomerController;
/*
|--------------------------------------------------------------------------
| 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');
});

Auth::routes();

Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::group(['middleware' => ['auth']], function() {
Route::resource('customer', CustomerController::class)->only(['create', 'store']);
});

Error show

Leave a Reply

Your email address will not be published. Required fields are marked *

− 1 = 5