Laravel

Two-column combination Unique validation in Laravel

Two-column combination Unique validation

In Laravel we need to manage unique column values in the database. In the database, many situations are available so we need to add validation on a single-column or Two-column combination Unique validation validation. So we need to add the Two-column combination Unique validation in Laravel.

Step 1 Setup the database and create the migration

Before Starting, need to create a database table migration, so let’s create a user table migration.

php artisan make:migration create_users_table

Now define the two columns in the user’s migration files database/migrations/2023_12_31_104137_create_users_table.php

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

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

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

After defining the column run the migration command.

php artisan migrate

Step 2 Create a User Model

php artisan make:model User

Step 3 Define the routes

Route::get('/users', [UserController::class, 'index']);
Route::get('/users/create', [UserController::class, 'create']);
Route::get('/users/store', [UserController::class, 'store']);
Route::get('/users/edit/{id}', [UserController::class, 'edit']);
Route::get('/users/update', [UserController::class, 'update']);

Step 4 Two-column combination Unique validation in the User Controller

php artisan make:controller  UserController 

Now we implement the two-column combination Unique validation while updating in the app/Http/Controllers/UserController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class UserController extends Controller {

    /**
     * 
     * @return type
     */
    public function index() {
        $users = User::paginate(10);
        return view('users.index', compact('users'));
    }

    public function create() {
        return view('users.create');
    }

    /**
     * 
     * @param Request $request
     * @param type $id
     * @return type
     */
    public function store(Request $request) {
        $validator = Validator::make($request->all(), [
                    'phone' => [
                        'required',Rule::unique('users')->where(function ($query) use($request) {
           return $query->where('phone', $request->phone)->where('email', $request->email);
         }),
                 ],
                        
                    'email' => 'required',
                    'name' => 'required',
        ],[
            'phone.unique' => 'Phone and email combination already exists',
        ]);
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        };
        $user = new User;
        $user->name = $request->name;
        $user->email = $request->email;
        $user->phone = $request->phone;
        if ($user->save()) {
            return redirect('users')->with('success', 'User created successfully');
            ;
        } else {
            return redirect()->back()->with('error', 'Some thing went wrong, please try again');
        }
    }

    /**
     * 
     * @param type $id
     * @return type
     */
    public function edit($id) {
        $user = $user = User::findOrFail($id);
        return view('

        users.edit', compact('user'));
    }

    /**
     * 
     * @param Request $request
     * @param type $id
     * @return type
     */
    public function update(Request $request) {
        $validator = Validator::make($request->all(), [
                    'phone' =>[ 
                        'required',Rule::unique('users')->where(function ($query) use($request) {
           return $query->where('phone', $request->phone)->where('email', $request->email)->where('id', '!=', $request->id);
         }),
                 ],
                        
                    'email' => 'required',
                    'name' => 'required',
        ],[
            'phone.unique' => 'Phone and email combination already exists',
        ]);
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        };
        $user = User::findOrFail($request->id);

        $user->update($request->all());
        if ($user->update($request->all())) {
            return redirect('users')->with('success', 'User updated successfully');
            ;
        } else {
            return redirect()->back()->with('error', 'Some thing went wrong, please try again ');
        }
    }

}

Step 4 Create view files

Now create a resources/users/create.blade.php and update the following code in that file.

<div class="container" style="background:#fff">
            <div class="row">
                <div class="col-md-12">
                    <h2 class="header-title">Users Create</h2>
                </div>
                <div class="col-md-12 mb-2">
                    @if(session()->has('error'))
                    <div class="text-danger">
                        {{ session()->get('message') }}
                    </div>
                    @endif
                    <form method="post" action="{{url('users/store')}}">
                        @csrf
                        <div class="col-md-6 mb-3">
                            <label for="name" class="form-label">Name</label>
                            <input type="text" class="form-control @error('name') is-invalid @enderror" id="name" placeholder="Please enter the name" name="name" value="{{ old('name') }}">
                            @error('name')
                            <div class="text-danger">{{ $message }}</div>
                            @enderror
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="email" class="form-label">Email</label>
                            <input type="email" class="form-control @error('email') is-invalid @enderror" id="email" placeholder="Please enter the email" name="email" value="{{ old('email') }}">
                            @error('email')
                            <div class="text-danger">{{ $message }}</div>
                            @enderror
                        </div>
                        <div class=" col-md-6 mb-3">
                            <label for="phone" class="form-label">Phone</label>
                            <input type="text" class="form-control @error('phone') is-invalid @enderror" id="phone" name="phone" placeholder="Please enter the phone number" value="{{ old('phone') }}">
                            @error('phone')
                            <div class="text-danger">{{ $message }}</div>
                            @enderror
                        </div>
                        <button type="submit" class="btn btn-primary">Submit</button>
                    </form>
                </div>
            </div>
        </div>

Create the resources/users/index.blade.php and show the users list.

<div class="container" style="background:#fff">
            <div class="row pt-5">
                <div class="col-md-12">
                    <div class="row">
                        <div class="col-md-6">
                            <h2 class="header-title">Users List</h2>
                        </div>
                        <div class="col-md-6">
                            <a href="{{ url('users/create') }}" class="btn btn-primary" style="float:right"><i class="fa fa-plus"></i> Add User</a>
                        </div>
                    </div>
                    <div class="col-md-12">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th scope="col">#</th>
                                    <th scope="col">Name</th>
                                    <th scope="col">Email</th>
                                    <th scope="col">Phone</th>
                                    <th scope="col">Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($users as $key => $user)
                                <tr>
                                    <th scope="row">{{$key}}</th>
                                    <td>{{$user->name}}</td>
                                    <td>{{$user->email}}</td>
                                    <td>{{$user->phone}}</td>
                                    <td>
                                        <a href="{{ url('users/edit/'.$user->id) }}" class="btn btn-primary"><i class="fa fa-pencil"></i></a>
                                    </td>
                                </tr>
                                @endforeach

                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

After that create the resources/users/edit.blade.php and show the user details which we want to edit the user.

<div class="container" style="background:#fff">
            <div class="row">
                <div class="col-md-12">
                    <h2 class="header-title">User Edit</h2>
                </div>
                <div class="col-md-12">
                    @if(session()->has('error'))
                    <div class="alert alert-danger">
                        {{ session()->get('message') }}
                    </div>
                    @endif
                    <form method="post" action="{{url('users/update')}}">
                        @csrf
                        <div class="col-md-6 mb-3">
                        <input type="hidden" name="id" value="{{$user->id}}"
                               <div class="col-md-6 mb-3">
                        <label for="name" class="form-label">Name</label>
                        <input type="text" class="form-control @error('name') is-invalid @enderror" id="name" placeholder="Please enter the name" name="name" value="{{ old('name', $user->name) }}">
                        @error('name')
                        <div class="text-danger">{{ $message }}</div>
                        @enderror
                </div>
                <div class="col-md-6 mb-3">
                    <label for="email" class="form-label">Email</label>
                    <input type="email" class="form-control @error('email') is-invalid @enderror" id="email" name="email" placeholder="Please enter the email" value="{{ old('email', $user->email) }}">
                    @error('email')
                    <div class="text-danger">{{ $message }}</div>
                    @enderror
                </div>
                <div class="col-md-6 mb-3">
                    <label for="phone" class="form-label">Phone</label>
                    <input type="text" class="form-control @error('phone') is-invalid @enderror" id="phone" name="phone" placeholder="Please enter the phone number" value="{{ old('phone', $user->phone) }}">
                    @error('phone')
                    <div class="text-danger">{{ $message }}</div>
                    @enderror
                </div>
                <button type="submit" class="btn btn-primary">Submit</button>
                </form>
            </div>
        </div>
    </div>

When running the http://127.0.0.1:8000/users/create url then show the users list like the following image.

Two-column combination Unique validation
Two-column combination Unique validation

Leave a Reply