Saturday, September 21, 2024
Google search engine
HomeLanguagesLaravel 8 – Form Validation Example

Laravel 8 – Form Validation Example

Laravel 8 form validation example tutorial. Here, we will show you how to validate form data in laravel 8 app.

In this tutorial, we will create employees detail form and submit form data in controller. And validate form data before insert/save to database.

Laravel 8 Example Form Validation

  • Step 1 – Download Laravel 8 Application
  • Step 2 – Setup Database with App
  • Step 3 – Create Model & Migration
  • Step 4 – Create Form Routes
  • Step 5 – Create Form Controller By Artisan Command
  • Step 6 – Create Form Blade File
  • Step 7 – Run Development Server

Step 1 – Download Laravel 8 Application

First of all download or install laravel 8 new setup. So, open terminal and type the following command to install new laravel 8 app into your machine:

composer create-project --prefer-dist laravel/laravel FormValidation

Step 2 – Setup Database with App

In this step, setup database with your downloded/installed laravel 8 app. So, you need to find .env file and setup database details as following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database-name
DB_USERNAME=database-user-name
DB_PASSWORD=database-password

Step 3 – Create Model & Migration

In this step, open again your command prompt. And run the following command on it. To create model and migration file for form:

php artisan make:model Employee -m

After that, open create_employees_table.php file inside FormValidation/database/migrations/ directory. And the update the function up() with following code:

    public function up()
    {
        Schema::create('employees', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email');
            $table->string('contact_no');
            $table->string('age');
            $table->timestamps();
        });
    }

Then, open again command prompt and run the following command to create tables into database:

php artisan migrate

Step 4 – Create Form Routes

In this step, open web.php file from routes direcotry. And update the following routes into web.php file:

use App\Http\Controllers\FormController;

Route::get('form', [FormController::class, 'index']);
Route::post('store-form', [FormController::class, 'store']);

Step 5 – Create Form Controller By Artisan Command

In this step, run the following command on command prompt to create controller file:

php artisan make:controller FormController

After that, go to app/http/controllers and open FormController.php file. And update the following code into it:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Employee;


class FormController extends Controller
{
    public function index()
    {
        return view('form');
    }

    public function store(Request $request)
    {
        
        $validatedData = $request->validate([
          'name' => 'required',
          'email' => 'required|unique:employees|max:255',
          'age' => 'required',
          'contact_no' => 'required|unique:employees|max:255',
        ]);

        $emp = new Employee;

        $emp->name = $request->name;
        $emp->email = $request->email;
        $emp->age = $request->age;
        $emp->contact_no = $request->contact_no;

        $emp->save();

        return redirect('form')->with('status', 'Form Data Has Been validated and insert');

    }
}

Step 6 – Create Form Blade File

Now, create form blade view file to display form and submit to database. So, Go to resources/views and create form.blade.php and update the following code into it:

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 8 Example Form Validation</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

</head>
<body>

<div class="container mt-4">

  @if(session('status'))
    <div class="alert alert-success">
        {{ session('status') }}
    </div>
  @endif

  <div class="card">
    <div class="card-header text-center font-weight-bold">
      <h2>Laravel 8 Form Validation Tutorial</h2>
    </div>
    <div class="card-body">
      <form name="employee" id="employee" method="post" action="{{url('store-form')}}">
       @csrf

        <div class="form-group">
          <label for="exampleInputEmail1">Name</label>
          <input type="text" id="name" name="name" class="@error('name') is-invalid @enderror form-control">
          @error('name')
              <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
          @enderror
        </div>        

        <div class="form-group">
          <label for="exampleInputEmail1">Email</label>
          <input type="email" id="email" name="email" class="@error('email') is-invalid @enderror form-control">
          @error('email')
              <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
          @enderror
        </div>        

        <div class="form-group">
          <label for="exampleInputEmail1">Age</label>
          <input type="number" id="age" name="age" class="@error('age') is-invalid @enderror form-control">
          @error('age')
              <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
          @enderror
        </div>        

        <div class="form-group">
          <label for="exampleInputEmail1">Contact No</label>
          <input type="number" id="contact_no" name="contact_no" class="@error('contact_no') is-invalid @enderror form-control">
          @error('contact_no')
              <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
          @enderror
        </div>

        <button type="submit" class="btn btn-primary">Submit</button>
      </form>
    </div>
  </div>
</div>  
</body>
</html>

The following below code will display validation error message on blade view file:

  @error('name')
  <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
  @enderror

Step 7 – Run Development Server

Last step, open command prompt and run the following command to start developement server:

php artisan serve

Then open your browser and hit the following url on it:

http://127.0.0.1:8000/form

Recommended Laravel Posts

RELATED ARTICLES

Most Popular

Recent Comments