CREATE AND VALIDATE FORM IN LARAVEL 9

Published March 07, 2022

In this tutorial we show how Laravel 9 Form Validation works with example. We see how to create a form from scratch and how to validate the form using built-in validation methods.

 

General rule in web application development is to perform validation on every input request either on the client side or the server side, so as to make sure that we are storing proper data into the database, avoid cross-site  scripting and database injections.

 

In Laravel we make use of the “validate()” method  from the “Illuminate\Http\Request” object to validate the form.  Validate() method checks the form values and throws an exception with proper error response message to the user if the validation has failed.

 

Following is a flow chart which shows how the validation works in Laravel 9.

 

form-request Larvel9



 

STEP 1 :Install Laravel Project

We first begin by creating a new project in the Laravel framework using Composer with the help of the following command.

composer create-project laravel/laravel --prefer-dist form-validation-example

Let’s get into the project folder

cd from-validation-example


 

STEP 2: CONFIGURE THE DATABASE CREDENTIALS

Now let's connect Laravel with MySQL Database by changing the details in .env file.

DB_CONNECTION=mysql

DB_HOST=localhost

DB_PORT=3306

DB_DATABASE=your_database_name

DB_USERNAME=your_database_username

DB_PASSWORD=your_database_password

 

STEP 3 : CREATE MODEL AND DATABASE MIGRATIONS

Now we need to create a model to define the table structure for storing the Form data into the Database. As our end objective is to create and validate form data and store it.

Let's use the following artisan command to create the model.

 

php artisan make:model Customer -m

 

We can find the  model created by the artisan command at the following location: “database/migrations/timestamp_create_customers_table.php”.

 Add the following piece of code to store the values in the database.

 

<?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('customer', function (Blueprint $table) {

            $table->id();

            $table->string('name');

            $table->string('email');

            $table->string('phone');

            $table->string('subject');

            $table->text('message');

            $table->timestamps();

        });

    }

    /**

     * Reverse the migrations.

     *

     * @return void

     */

    public function down()

    {

        Schema::dropIfExists('forms');

    }

}


 

Now add the following code to app/Model/Customer.php. Here we are adding migration values such as ‘name’,’email’,’phone’,’subject’ and ‘message’ under the ‘$fillable’ array, in order to tell the model that only these value can we stored. 

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Database\Eloquent\Model;

class Customer extends Model

{

    use HasFactory;

    public $fillable = [

        'name', 

        'email', 

        'phone', 

        'subject', 

        'message'

    ];

}

 

Use the artisan command to run the migrations.

 

php artisan migrate

 

STEP 4 : CREATE  CONTROLLER

Create a controller CustomerFormController using artisan command.

php artisan make:controller CustomerFormController

 

Add the following code into app/Http/Controller/CustomerFormController.php  file

 

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Customer;

 

class CustomerFormController extends Controller

{

// Create Form

public function show(Request $request) {

    return view('form');

  }

  // Store Form data in database

  public function store(Request $request) {

      // Form validation

      $this->validate($request, [

          'name' => 'required',

          'email' => 'required|email',

          'phone' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|min:10',

          'subject'=>'required',

          'message' => 'required'

       ]);

      //  Store data in database

      Form::create($request->all());

      return back()->with('success', 'Your form has been submitted.');

  }

  

}


 

Firstly we are importing the Customer model to map Customer data. We have two functions in the controller.

show() : This function renders the form in Laravel view.

store() : Validate the Laravel form and store the form data in the MySQL database.

 

STEP 5 : CREATE ROUTES

Now we need two routes for the form, first with the GET method to show form in the view and the second route with POST method to handle validation, error, success and store  the information into the database.

 

Add the routes to route/web.php

 

<?php

use Illuminate\Support\Facades\Route;

/*

|--------------------------------------------------------------------------

| 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::group(['namespace' => 'App\Http\Controllers'], function () {

    Route::get('/', 'CustomerFormController@show');

    Route::post('/form', 'CustomerFormController@store')->name('validate.form');

});


 

STEP 6 : CREATE VIEW 

Now we have to create a view file in Laravel to work with Laravel Forms. Here we are using the  Bootstrap 5 CSS framework to design the forms in attracted design. Go to resources/views/ folder and create a form.blade.php file, then, update the following code in resources/views/form.blade.php file.

<!DOCTYPE html>

<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>

    <meta charset="utf-8">

    <meta name="viewport" content="width=device-width, initial-scale=1">

    

    <title>Form Validation in Laravel</title>

    

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css">

    <link rel="stylesheet" type="text/css" href="{{ asset('css/style.css') }}">

</head>

<body>

    <div class="container mt-5">

        @if(Session::has('success'))

            <div class="alert alert-success text-center">

                {{Session::get('success')}}

            </div>

        @endif    

        <form  method="post" action="{{ route('validate.form') }}" novalidate>

            @csrf

            <div class="form-group mb-2">

                <label>Name</label>

                <input type="text" class="form-control @error('name') is-invalid @enderror" name="name" id="name">

                @error('name')

                    <span class="invalid-feedback" role="alert">

                        <strong>{{ $message }}</strong>

                    </span>

                @enderror

            </div>

            <div class="form-group mb-2">

                <label>Email</label>

                <input type="email" class="form-control @error('email') is-invalid @enderror" name="email" id="email">

                @error('email')

                    <span class="invalid-feedback" role="alert">

                        <strong>{{ $message }}</strong>

                    </span>

                @enderror

            </div>

            <div class="form-group mb-2">

                <label>Phone</label>

                <input type="text" class="form-control @error('phone') is-invalid @enderror" name="phone" id="phone">

                @error('phone')

                    <span class="invalid-feedback" role="alert">

                        <strong>{{ $message }}</strong>

                    </span>

                @enderror

            </div>

            <div class="form-group mb-2">

                <label>Subject</label>

                <input type="text" class="form-control @error('subject') is-invalid @enderror" name="subject" id="subject">

                @error('subject')

                    <span class="invalid-feedback" role="alert">

                        <strong>{{ $message }}</strong>

                    </span>

                @enderror                

            </div>

            <div class="form-group mb-2">

                <label>Message</label>

                <textarea class="form-control @error('message') is-invalid @enderror" name="message" id="message" rows="4"></textarea>

                @error('message')

                    <span class="invalid-feedback" role="alert">

                        <strong>{{ $message }}</strong>

                    </span>

                @enderror                     

            </div>

            <div class="d-grid mt-3">

              <input type="submit" name="send" value="Submit" class="btn btn-dark btn-block">

            </div>

        </form>

    </div>

</body>

</html>

 

Finally we add custom CSS to our project inside the public directory. Create /assets/css/styles.css and add the following code in the file.

 

.container {

    max-width: 500px;

    margin: 50px auto;

    text-align: left;

    font-family: sans-serif;

}

form {

    border: 1px solid #1A33FF;

    background: #ecf5fc;

    padding: 40px 50px 45px;

}

.form-control:focus {

    border-color: #000;

    box-shadow: none;

}

label {

    font-weight: 600;

}

.error {

    color: red;

    font-weight: 400;

    display: block;

    padding: 6px 0;

    font-size: 14px;

}

.form-control.error {

    border-color: red;

    padding: .375rem .75rem;

}

 

 

STEP 7: START DEVELOPMENT SERVER AND TEST APPLICATION

Let's test our application. Run the following command to start the development server. 

 

php artisan serve

 

To see the application hit the following URL in the browser.
 

http://127.0.0.1:8000/

 

Laravel 9 Form validation

 

CONCLUSION

Validating a form is easy in Laravel with its eloquent infrastructure,  so far we have understood how to create a form with Bootstrap and implement server side form validation in Laravel application

 

Tags: Laravel 9, Form Validation, Laravel PHP, Create Forms in Laravel

 

Download Source code

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

250 Views