How to Implement Exists Validation in Laravel 10 Form

Last Updated on by in Laravel

In this comprehensive guide, you will learn how to implement the Exists Validation in a Laravel form using the Laravel Exists validation.

The exists rule ensures that the submitted value for a field exists in a specified database table column. This validation is essential for maintaining data integrity and ensuring that the data being submitted aligns with your database records.

In this tutorial, you will cover:

  • Setting up the Laravel application: Preparing your application with the necessary configurations.
  • Defining the exists rule: Specifying the table and column for the `exists` rule in your form validation.
  • Validating form input: Implementing form validation in your controller using Laravel’s built-in methods.
  • Handling validation results: Creating appropriate responses for valid and invalid form submissions.

By the end of this tutorial, you will be able to use the exists rule to validate your form inputs against database records effectively, enhancing your application’s data consistency and user experience. Let’s begin!

Laravel 10 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

No matter on which machine you are creating the laravel app, one thing is imperative that you have to install Composer globally.

After doing the needful, lay the foundation of this tutorial by installing the fresh laravel application.

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

Database Connection

In this step, you have to make the database connection by adding the database details in .env file.

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

If you are using MAMP local server in macOs; make sure to append UNIX_SOCKET and DB_SOCKET below database credentials in .env file.

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

Create Migration and Model

In this step, we will run the command and generate migration and model files.

php artisan make:model Blog -m

Get into the database/migrations/create_blogs_table.php and insert the values as suggested.

<?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');
    }
}

Similar value has to be updated inside the 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',
    ];
}

Initialize the migration using the php artisan command.

php artisan migrate

Setting Up Controller

Get into the terminal and run the command to generate a new controller.

php artisan make:controller BlogController

Head over to the new controller on the following path, the app/Http/Controller/BlogController.php file and update the given code into 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 the next step, you have to go to routes/web.php and create the routes for handling view and laravel exists validation.

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\BlogController;

/*
|--------------------------------------------------------------------------
| 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::get('/', [
    BlogController::class,'index'
]);
Route::post('validate-exists', [
    BlogController::class,'store'
])->name('validate.exists');

Set Up Blade View Template

Go to resources/views/ directory, after that create a index.blade.php within this file define the following code.

<!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 are using the global old helper; it helps display the old input within a blade template.

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

Also, instead of specifying the table name directly, you may specify the Eloquent model which should be used to determine the table name.

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

Start Laravel Application

Last but not least start the laravel app using the following command.

php artisan serve

You can open the app on the following url for testing the form.

http://127.0.0.1:8000

How to Implement Exists Validation in Laravel Form

Summary

You now understand how to use the exists validation rule in Laravel to ensure form input data matches your database records.

This validation helps maintain data integrity and improves the overall user experience by preventing invalid data from being stored.

Go ahead and apply this knowledge to your projects to enhance your form handling!

Age calculator tool

🎂✨ Discover your age in detail and with countdown to your next birthday with fun facts! 🎈🎉

Calculate your age now!
Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.