How to Add Exists Validation in Laravel 8 Input Field

In this Laravel Exists validation tutorial, we will learn how to integrate exists validation in the laravel form. We will explain how to use exists validation rules in relation to a form input field.

As per the common notion, form validation is an integral part of web development. Let’s assume if you want to check the student name exists on the database table in the laravel app. In this particular scenario, laravel exists, validation plays the vital and significant role.

To give you the complete demo, we will create an elementary form and show you how to add exists validation in laravel with the help of the laravel validator’s exists method.

Laravel 8 Exists Input Validation Example

  • Step 1: Create Laravel Project
  • Step 2: Add Database Credentials
  • Step 3: Build Model and Migration
  • Step 4: Run Database Migration
  • Step 5: Create Controller File
  • Step 6: Register New Routes
  • Step 7: Create Blade View File
  • Step 8: Test Laravel App

Create Laravel Project

Composer is a modern tool and provides outstanding support for laravel application development; execute the command to create the new laravel app.

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

Add Database Credentials

The best way to create a database connection with laravel is to add the database credentials in the .env config file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db_name
DB_USERNAME=db_username
DB_PASSWORD=db_password

Build Model and Migration

In this step, we will ensure to define the model and migration files; by doing this, we will determine the logical structure of the table that we will put into the database.

php artisan make:model Student -m

On the other hand, add the similar table properties in the app/Student.php model file.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    use HasFactory;
    public $fillable = [
        'student_name',
    ];    
}

Once the migration file is created, open database/migrations/create_students_table.php file and and add the table properties.

<?php

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

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

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

Run Database Migration

In this step, you need to run the migration to create the table in the database.

php artisan migrate

Create Controller File

In this step, you require to run the command to create the new controller file where you can write the code to add the exists validation with other validation types.

php artisan make:controller StudentController

Now, open the app/Http/Controller/StudentController.php and insert the following code within the file.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Student;


class StudentController extends Controller
{
    public function index() {
        return view('welcome');
    }

    public function store(Request $request) {
       $validator = $this->validate($request, [
          'student_name' => 'required|exists:students,created_at'
       ]);

       if($validator) {
        Student::create($request->all());
       }
       
       return back()->with('success', 'Student has been added.');
    }
}

Register New Routes

Go to routes/web.php file, import controller for defining the routes that will execute the code mentioned in the controller.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\StudentController;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::get('/', [StudentController::class, 'index']);

Route::post('form', [StudentController::class, 'store'])->name('student.validate');

Create Blade View File

Let us create the blade view file, open the resources/views/welcome.blade.php file, then add the provided code within the file.

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>Laravel Exists Validation Example</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>
    <div>
        <form action="{{ route('student.validate') }}" method="post">
            @csrf
            <div>
                <input class="form-control" name="student_name" value="{{ old('student_name') }}">
                
                @if($errors->has('student_name'))
                  <span class="text-danger">{{ $errors->first('student_name') }}</span>
                @endif
            </div>

            <div class="mt-2">
                <button class="btn btn-primary">Save</button>
            </div>
        </form>
    </div>
</body>

</html>

Test Laravel App

To test the exists validation, you must run the laravel development server; after that, start the laravel app using the provided URL.

php artisan serve
http://127.0.0.1:8000

How to Add Exists Validation in Laravel 8 Input Field

Summary

Laravel offers a friendly method called exists, which is best for checking if your query returns any records. In this laravel exists validation example, you have learned how to implement exists validation rules in the laravel form field to check if the provided record exists in the database table.