How to Implement Exists Validation in Laravel 9 Form

We will learn in this tutorial how to implement existing validation in a Laravel form using the ‘exists‘ method in Laravel.

The Laravel ecosystem is developer-friendly and also, helps web developers to build desired functionality with minimum effort.

For instance, creating forms and adding validation in Laravel is easy using a validator. We will cover the ‘exists‘ validator example in this tutorial.

We will build a basic form with the title property and check if the title property is present in the database table. Generally the EXISTS operator checks for the existence of records in a subquery.

Likewise, The exists() field explicitly checks the field under validation rule concerning a given database table. If, anyhow, the column option is not defined, the field name will be used.

Laravel 9 Exists Validation Example

  • Step 1: Download New Laravel App
  • Step 2: Database Connection
  • Step 3: Create Migration and Model
  • Step 4: Setting Up Controller
  • Step 5: Create Routes
  • Step 5: Set Up Blade View Template
  • Step 6: View App

Download New Laravel App

The first step is to create a new Laravel app and install composer globally. This lays the foundation for a fresh Laravel application.

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

Database Connection

Next step is to create the database connection by updating your database details in .env file.

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=laravel_db
DB_USERNAME=root
DB_PASSWORD=

In case you are using the MAMP local server in Mac operating system, ensure to add UNIX_SOCKET and DB_SOCKET database credentials in your .env file as shown below.

UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock

Create Migration and Model

In the next step, you have to run the command below and generate migration and model files.

php artisan make:model Blog -m

Open your database/migrations/create_blogs_table.php and add the values as given below.

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateBlogsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('blogs', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('blogs');
    }
}

Similarly, values need to be updated in your app/Blog.php file.

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Blog extends Model
{
    use HasFactory;
    public $fillable = [
        'title',
    ];
}

Now, initialize the migration using the php artisan command.

php artisan migrate

Setting Up Controller

Open your terminal and type in the command below to create a new controller.

php artisan make:controller BlogController

Now, open the new controller file at the location, app/Http/Controller/BlogController.php and update the code below in it.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Blog;

class BlogController extends Controller
{
    public function index() {
        return view('index');
    }
    public function store(Request $request) {
       $validator = $this->validate($request, [
          'title' => 'required|exists:blogs,created_at'
       ]);
       if($validator) {
          Blog::create($request->all());
       }
       
       return back()->with('success', 'Blog created.');
    }
  
}

Create Routes

In this step, you need to go to routes/web.php and add the routes to handle view and Laravel exists validation.

Set Up Blade View Template

Open your resources/views/ directory, and then create a index.blade.php in this file adding the code given below.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Integrate Exists Validation in Laravel</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-5">
        <form action="{{ route('validate.exists') }}" method="post">
            @csrf
            <div class="form-group">
                <input class="form-control" name="title" value="{{ old('title') }}">
                
                @if($errors->has('title'))
                  <span class="text-danger">{{ $errors->first('title') }}</span>
                @endif
            </div>
            <div class="d-grid mt-3">
                <button class="btn btn-dark">Submit</button>
            </div>
        </form>
    </div>
</body>
</html>

We will use the global old helper, it will help display the old input inside a blade template.

You will define the database column name that will be used by the validation rule by appending it right after the database table name.

Moreover, instead of specifying a table name directly, you can state the Eloquent model which can be used to determine the table name.

'id' => 'exists:App\Models\Blog,id'

Start Laravel Application

Finally, start your Laravel app using the command given below.

php artisan serve

You may open your app using the URL below to test the form.

http://127.0.0.1:8000
How to Implement Exists Validation in Laravel Form

Summary

This tutorial explains how to validate an input field value using the Laravel exists method. Moreover, we have learnt the basic use of exists rule in Laravel.