Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
Unique Validation in laravel 8

Unique validation on Update in Laravel with example

Aman Jain, June 19, 2022November 17, 2023

In this article we will learn to handle the unique validation on update in laravel.As we know Laravel support validation for database operations. Laravel unique validation validates the table column uniqueness using unique validation. In this tutorial we will learn about the unique validation to table columns and also while updating the value too.

you can use this to check the uniqueness of email, username , name and id etc in any version of laravel 5, laravel 6, laravel 7, laravel 8 and laravel 9.

We will use one Laravel rules to validate the email here

  1. unique

So, it can be use in any controller or route as below

unique:table_name,column_name,except_column_id,column_name_in_table

so to use it at the time of update we can use as follow

'email' => 'required|email|unique:users,email,2,id'

Here unique is the rule name, users is table name, email is column name, 2 is value of id field which we want to exclude(useful at the time of update record), id name of column to match with(2).

Lets’ take a example Users table:

Table Name : Users

idemailstatusupdated_atcreated_at
unique:users,email,2,id
<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class PostController extends Controller
{

 function validateUnique($request Request){
   $validator = Validator::make($request->all(), [
            'email' => 'required|email|unique:users,email,2,id'
        ]); 
}
}

Here, we used unique:users unique is rule name and users is table name.

Column name is different from form name

if column name is different from column name of table then we can pass second parameter to unique validation

 $validator = Validator::make($request->all(), [
           'form_name' => ['required','unique:users,email']
  ]); 

Unique validation on update with Rule

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Contracts\Validation\Rule;


class ArticleController extends Controller
{

 function validateUnique($request Request){
   $authUser = User::find(1);
   $validator = Validato'r::make($request->all(), [
            'email' => ["required","email",
                       Rule::unique('users')->ignore($authUser->id)]
        ]); 
}
}

Let’s learn with simple example

Step 1 : Create a controller

Create the controller and add the necessary imports and class. You can create by Laravel artisan or manually.

php artisan make:controller PostController

Now, add use Illuminate\Support\Facades\Validator; and methods

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Validator;

class PostController extends Controller
{

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

    public function save(Request $request, $id='')
    {
        $validator = Validator::make($request->all(), [
            'name' => ['required','unique:posts,name,'.($id=='' ? 0 :  $id).',id']
            
        ]); // create the validations
        if ($validator->fails())   //check all validations are fine, if not then redirect and show error messages
        {
            
            return back()->withInput()->withErrors($validator);
            // validation failed redirect back to form

        }
        else
        {
            //handle the form 
        }  
    }
   
}

Here, we added image validation using image,mimes and dimension.

Step 2 : Create Routes

Second step is to create the routes to show the form and submit the form

<?php

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


Route::get('/create-post',[PostController::class, 'create']);
Route::post('/save-post',[PostController::class, 'save']);
Route::post('/save-post/$id',[PostController::class, 'save']);

Here, we created 3 routes one for show the form, second for create new post and third for updating the form.

Step 3 : Create the view for form

We have created routes and controller and now we need to create the form so we are creating the view file for it.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Readerstacks laravel 8 unique validation</title>
 <link href="//netdna.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />
   </head>
    <body class="antialiased">
    <div class="container">
    <!-- main app container -->
    <div class="readersack">
      <div class="container">
        <div class="row">
          <div class="col-md-6 offset-md-3">
            <h3>Laravel 8 unique validation - Readerstacks</h3>
            @if ($errors->any())
                <div class="alert alert-danger">
                    <ul>
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif
            <form method="post" action="{{url('submit-post')}}" name="registerform">
             <div class="form-group">
                <label>Name</label>
                <input type="text" name="name" value="{{old('name')}}"  class="form-control" />
                @csrf
              </div>
               
            
              <div class="form-group">
                <button class="btn btn-primary">Post</button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
    <!-- credits -->
    <div class="text-center">
      <p>
        <a href="#" target="_top">Laravel 8 unique validation </a>
      </p>
      <p>
        <a href="https://readerstacks.com" target="_top">readerstacks.com</a>
      </p>
    </div>
  </div>
    </body>
</html>

Related

Php Laravel Laravel 9 laravelonupdatephpuniquevalidation

Post navigation

Previous post
Next post

Related Posts

Php Image Validation in laravel 8

How to use image validation in Laravel 8 with example

November 21, 2021January 26, 2022

Laravel provides multiple ways to validate a form or a image in form with it’s own validation library. In this tutorial we will learn about the image validation for specific extension and file size. In this tutorial i will use a simple form and a image file input field to…

Read More
Php Laravel Redirect from Http to Https Secure URL

Laravel Redirect from Http to Https Secure URL

August 26, 2022March 16, 2024

To redirect from http to https secure url in laravel we can achieve by multiple ways. While deploying application to server we need to make our website secure and robust so attackers can not attack easily on website. In this tutorial we will learn to redirect the http to https…

Read More
Php Laravel encrypt and decrypt strings

How to encrypt and decrypt string in laravel 8 ?

January 26, 2022January 26, 2022

Laravel provides inbuilt library to encrypt and decrypt the strings. Laravel usage OpenSSL to provide AES-256 encryption which creates long encrypted string. Encryption and decryption is a technique to hide the useful some information in a form which is not readable. In this tutorial i will show you to encrypt…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
  • Understanding High Vulnerabilities in Software: A Week of Insights
  • Blocking Spam Requests with LaraGuard IP: A Comprehensive Guide
  • Enhancing API Development with Laravel API Kit
  • Exploring the Future of Web Development: Insights from Milana Cap
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version