This tutorial will teach you how to implement existing validation in the laravel form using the laravel exists method.
Laravel ecosystem is developer-friendly at the same time, helps web developers to build desired functionality effortlessly.
For example, building forms and adding validation in Laravel is easy with a validator in this Laravel exists validator example.
We will create a basic form with the title property and check if the title property exists in the database table. In general the EXISTS operator is used to check for the existence of any record in a subquery.
Similarly, 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
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

Summary
In this tutorial, we have learned how to validate an input field value with the laravel exists method. Moreover, looked at how the basic usage of exists rule is applied in laravel.