Laravel 10 Form Validation using Validation Rules Example

If you are developing a Laravel web application and need to ensure that the data submitted through a form is validated before storing it in the database, then this tutorial is for you. In this tutorial, you will learn how to implement form with validation and securely insert/store the validated data in a Laravel 10 application.

Laravel 10 Form Validation using Validation Rules Example

By following the steps outlined, you can validate form data before store/insert in database in laravel 10 apps:

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

Step 1 – Setup New Laravel 10 Application

First of all, start your terminal to download or install Laravel 10 new setup. Execute the following command into it to install new Laravel 10 app into your system:

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

Step 2 – Configure Database with App

In this step, Configure your database with your apps. So, visit your app root directory and find .env file. Then configure database details as follows:

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 – Add Form Routes

In this step, Visit your routes directory and open web.php file in any text editor. And add the following routes into web.php route 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, execute the following command on terminal/command prompt/command line to create controller file for your laravel applications; is as follow:

php artisan make:controller FormController

Now, visit your laravel directory 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 10 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 10 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

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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