Laravel 5.8 Form Request Validation

There are plenty of validation methods available to validate the form data request with Laravel 5.8. By default Laravel's base controller class uses a ValidatesRequests trait which provides a way to validate incoming HTTP request with many validation rules.

# Form Request Validation

For more complex validation scenarios, you may wish to create a "form request". Form requests are custom request classes that contain validation logic. Refer more about form request validation to see from the Laravel 5.8 Documentation.

In this tutorial, You'll learn to implement validation for Form Request. Follow the step by step guide to create the application.

  1. Install Laravel 5.8

    First, let install Laravel 5.8 using the following command (Make sure you have installed composer in your PC). Click on Install Composer If you haven't installed Composer on your PC.

    composer create-project --prefer-dist laravel/laravel formRequestValidation
  2. Configure Database Details

    You need to create the database at MYSQL and then we need to connect that database to the Laravel project (You can also use phpmyadmin to create the database). Open the .env file inside Laravel project and add the database credentials as below.

    .env

    DB_CONNECTION=mysql
    DB_HOST=127.0.0.1
    DB_PORT=3306
    DB_DATABASE='Your DB Name'
    DB_USERNAME='Your DB UserName'
    DB_PASSWORD='Your DB Password'
  3. Create Form Requests

    Form requests are used to create custom validation logics. To create a form request class type the command in your terminal as below.

    php artisan make:request FormDataRequest

    The generated class will be stored in in the app/Http/Requests file directory. Open FormDataRequest.php from the directory and add the validation rules inside the rules method and the custom messages inside the messages method.

    app\Http\Requests\FormDataRequest.php

    <?php
    namespace App\Http\Requests;
    
    use Illuminate\Foundation\Http\FormRequest;
    
    class FormDataRequest extends FormRequest
    {
    
        public function authorize()
        {
            return true;
        }
    
        public function messages()
        {
            return [
                'name.required' => 'The name is Required.',
                'detail.required'  => 'The detail is Required.',
                'price.required'  => 'The price is Required.',
            ];
        }
    
    
        public function rules()
        {
            return [
                'name' => 'bail|required|max:255',
                'detail' => 'required|max:255',
                'price' => 'required|numeric',
            ];
        }
    }
    

    Now, You need to return true; from the authorize() method. If the authorize method returns false, a HTTP response with a 403 status code will be returned.

    public function authorize()
    {
       return true;
    }
  4. Create the migration file.

    Type the following command at your terminal to create the model and migration files.

    php artisan make:migration create_form_data_table --create=formData

    The migration will be created under "database/migrations". Edit the file with the code below to create formData Table.

    create_form_data_table.php

    <?php
    use Illuminate\Support\Facades\Schema;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Database\Migrations\Migration;
    
    class CreateFormDataTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('formData', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->string('name');
                $table->string('detail');
                $table->integer('price');
                $table->timestamps();
            });
        }
    
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('formData');
    }
    }

    Type the following command to run the migration.

    php artisan migrate

    Create the FormData model using the following command.

    php artisan make:model FormData

    The model wil be generated in "app/FormData.php" Now, we will write the schema inside FormData.php file.

    app/FormData.php

    <?php
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    
    class FormData extends Model
    {
        protected $table = 'formData';
        protected $fillable = ['name', 'detail', 'price'];
    }
  5. Create FormDataController

    Type the following command at your terminal to create FormDataController.php file in controllers

    php artisan make:controller FormDataController

    app/Http/Controllers/FormDataController.php

    <?php
    namespace App\Http\Controllers;
    
    use App\FormData;
    use App\Http\Requests\FormDataRequest;
    
    class FormDataController extends Controller
    {
    
        public function index()
        {
            return view('index');
        }
    
        public function save(FormDataRequest $request)
        {
            $validatedData = $request->validated();
            FormData::create($validatedData);
    
            return redirect()->back()->with('success', 'The Form Data is successfully inserted to the Database!');
        }
    
    }

    Now, write the two routes in routes -> web.php file.

    Route::get('/', 'FormDataController@index')->name('form.index'); Route::post('form', 'FormDataController@save')->name('form.save');
  6. Create the view Files

    create the following five files inside resources -> views folder.

    1. layout.blade.php
    2. index.blade.php

    resources/views/layout.blade.php

    <!DOCTYPE html>
    <html>
    <head>
        <title>Laravel 5.8 Form Request Validation Application - bishrulhaq.com</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    </head>
    <body>
    
    <div class="container">
        <div class="row" style="margin-top: 20px;">
            <div class="col-12">
                @yield('content')
            </div>
        </div>
    </div>
    
    </body>
    </html>
    

    resources/views/index.blade.php

    @extends('layout')
    @section('content')
    
        <div class="card">
            <div class="card-header">
                Insert Data
            </div>
            <div class="card-body">
    
                @if(session()->has('success'))
                    <div class="alert alert-success">
                        {{ session()->get('success') }}
                    </div>
                @endif
    
                @if ($errors->any())
                    <div class="alert alert-danger">
                        <ul>
                            @foreach ($errors->all() as $error)
                                <li>{{ $error }}</li>
                            @endforeach
                        </ul>
                    </div>
                @endif
                <form method="post" action="{{ route('form.save') }}">
                    <div class="form-group">
                        @csrf
                        <label for="name">Name : </label>
                        <input type="text" class="form-control" name="name"/>
                    </div>
                    <div class="form-group">
                        <label for="price">Detail : </label>
                        <input type="text" class="form-control" name="detail"/>
                    </div>
                    <div class="form-group">
                        <label for="quantity">Price : </label>
                        <input type="text" class="form-control" name="price"/>
                    </div>
                    <button type="submit" class="btn btn-primary">Save Data</button>
                </form>
            </div>
        </div>
    @endsection
    

    Finally, Laravel 5.8 Form Request Validation Application is ready to run. Type the following command in your terminal to run the application.

    php artisan serve

Hope this tutorial helped you! Feel free to drop your opinion at the comment section.