How to use ‘unique’ for database columns validation in Laravel

When you want to ensure that a field is unique in the database, and to avoid adding the same value to a column twice, such as the email for a customer. You can use the unique keyword to check database columns validation in Laravel. Lets check the syntax and files of how and where to use the keyword in Laravel validation.

We will start with how to define a field in the database to assure for database columns validation in Laravel.

Database Columns Migrations

To assure a new field that is being added to the database should be unique, you can add the unique( ) during database migration.

$table->string('cust_email')->unique();

This generates an index in the database which prevents two rows in the table having the same email when you try and save a record. This works like the validation in phpmyadmin databases. When you define a field as unique, it avoids same entries in that column. This is where validation rules come into play.

Database Columns Input Validation

To validate a form that the user has to fill, to create a new record you can either validate directly in the controller method for save and update, or you can move the validation into a form request class. Using a form request class makes your controller look cleaner and keeps the validation rules all in one place.

You can use the artisan command to create a new form request class, in our case we will call it SavePostRequest.

php artisan make:request SavePostRequest

This injects the newly created class into your save and update methods in the RecordsController as shown below.

<?php

namespace App\Http\Controllers;

use App\Http\Requests\SavePostRequest;

class RecordsController extends Controller
{
    public function save(SavePostRequest $request)
    {
        // Store model
    }

    public function update(SavePostRequest $request, Records $records)
    {
        // Update model
    }
}

Now you can add the unique validation rule to the SavePostRequest class. If you want to make the email a required attribute, and then ensure that the email is unique in the posts table. The rule has a format of unique:table,column.

public function rules()
{
    return [
	    'email' => 'required|unique:records,email'
    ];
}

The code snipper shown above, follows the rule format. Here unique keyword is use don the ‘records’ table and ’email’ column. This ensures adding unique emails for all users in the records table.

To avoid validation errors during updates. The rule can be customized as explained here.