Laravel 8 Validation example from scratch

In this tutorial, we will learn how to validate the POST data using Laravel validation methods with HTML form. Laravel provides various methods to validate the incoming HTTP request with different validation rules. Let's get started.

Step 1: Install Laravel

In this step, we will install a fresh Laravel project. Before we begin, make sure the composer is installed in your system. To install the fresh Laravel project, Enter the below command.

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

Step 2: Setup database connection

Open your fresh installed project in the code editor and rename .env.example file to .env. Once you are done with renaming, edit the .env file, and update your database credentials. 

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=blog
DB_USERNAME=root
DB_PASSWORD=

I have set up the database connection. I don't have any MySQL password so, I left blank.

Step 3: Create Migration & Model

Next, we will be creating the model and migration for the Post table. Enter the below command to create migration and model

php artisan make:migration Post -m

-m will create the post model.

Now open database/migrations/2021_01_11_111944_create_posts_table.php and update the posts migration file.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('slug');
            $table->string('description');
            $table->timestamps();
        });
    }

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

Now enter the below command to migrate your table.

php artisan migrate

Step 4: Create Routes

In this step, Let's quickly create routes for our post. Below is the code for post routes

routes\web.php

Route::get('create-post','[email protected]')->name('post.create');
Route::post('create-post','[email protected]')->name('post.store');

Step 5: Create Controller

In this step, we will create a controller for posts. Enter the following command to create the controller

php artisan make:controller PostController

Now create two methods for the post. Create a method to show the form and store method where we write the validation logic and save the post data. Copy and paste the below code in your post controller

app\Http\Controllers\PostController.php

<?php

namespace App\Http\Controllers;

use App\Post;
use Illuminate\Support\Str;
use Illuminate\Http\Request;

class PostController extends Controller
{
    public function create()
    {
        return view('create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'description' => 'required',
        ]);

        $request->merge([
            'slug' => Str::slug($request->name)
        ]);

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

        return back()->with('success','Post Created Successfully');
    }
}

$request->validate(); function will validate the input data. If it is empty then it will redirect back to the form with errors as well as old input data. Now let's create a post form.

Step 6: Create a View file

In this step, we will create a post form.

resources/views/create.blade.php

@extends('layouts.app')
@section('content')
    <div class="container">
        <div class="row">
            <div class="col-md-6 offset-3 mt-5">
                <div class="card">
                    <div class="card-header">
                        <h5>Laravel 8 Form Validation</h5>
                    </div>
                    <div class="card-body">
                        @if (count($errors) > 0)
                            <div class="alert alert-danger">
                                <ul>
                                    @foreach ($errors->all() as $error)
                                        <li>{{ $error }}</li>
                                    @endforeach
                                </ul>
                            </div>
                        @endif

                        @if ($message = Session::get('success'))
                            <div class="alert alert-success alert-block">
                                <button type="button" class="close" data-dismiss="alert">×</button>
                                <strong>{{ $message }}</strong>
                            </div>
                        @endif

                        <form action="{{ route('post.store') }}" method="post" enctype="multipart/form-data">
                            @csrf
                            <div class="form-group">
                                <label><strong>Name : </strong></label>
                                <input type="text" name="name" class="form-control" value="{{ old('name') }}">
                            </div>
                            <div class="form-group">
                                <label><strong>Description : </strong></label>
                                <textarea class="form-control" name="description">{{ old('description') }}</textarea>
                            </div>
                            <div class="form-group text-center">
                                <input type="submit" class="btn btn-success" name="submit">
                            </div>
                        </form>                     
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection