Laravel Unique Validation on Multiple Columns Example
Jan 24, 2023 . Admin
Hi Dev,
In this article, I'll demonstrate laravel unique validation on a variety of columns. This page contains information about the two-field, exclusive Laravel validation. You'll see a simple illustration of laravel unique column validation in this article. Learn how to modify two columns for specific Laravel validation.
I'll explain how to utilise unique validation on a number of fields in a Laravel 6, Laravel 7, Laravel 8, or Laravel 9 application in this section. I'll give you several options for including two columns of unique validation in your application. Both at create time and edit time, you can add unique validation.
All company has a distinct login, hence sometimes we need to provide unique validation with multiple fields for username etc. Then, if you want to check a unique email address or username, you must manually build a database query and utilise an if condition. However, Laravel offers "unique" rules that make it simple to apply unique validation.
Basically, you can create your own request class using bellow command:
Create Request Class:php artisan make:request StoreUserRequest php artisan make:request UpdateUserRequestController File Code:
<?php namespace App\Http\Controllers; use App\Http\Requests\StoreUserRequest; use App\Http\Requests\UpdateUserRequest; use App\User; class UserController extends Controller { public function store(StoreUserRequest $request) { /* Do Something */ } public function update(UpdateUserRequest $request, User $user) { /* Do Something */ } }
Now you can see bellow solution one by one and you can use anyone that you require for unique validation.
Example 1: Store Unique Validation on Multiple Columns<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Validation\Rule; class StoreUserRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'name' => 'required', 'email' => 'required|email', 'username' => [ 'required', Rule::unique('users') ->where('company_id', $this->company_id) ] ]; } }Example 2: Update Unique Validation on Multiple Columns app/Http/Requests/UpdateUserRequest.php
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class UpdateUserRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return false; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'name' => 'required', 'email' => 'required|email', 'username' => [ 'required', Rule::unique('users') ->ignore($this->user) ->where('company_id', $this->company_id) ] ]; } }
I hope it can help you...