mikefolu
mikefolu

Reputation: 1333

Laravel - How to validate Unique Rule Request as case sensitive

I have this Rules in my Laravel-5.8

Rules: create

 public function rules()
 {
   return [
    'location_name' => [
        'required',
        'string',
        'min:3',
        'max:80',               
        Rule::unique('hr_work_locations', 'location_name', 'company_id')
    ],          

  ];
 }

Rules: edit

 public function rules()
 {
    return [
    'location_name' => [
        'required',
        'string',
        'min:3',
        'max:80',               
        Rule::unique('hr_work_locations', 'location_name', 'company_id')->ignore($this->work_location)
    ],          
  ];
 }

from the rules,location_name is unique for each company (company_id). Also in the edit rules,

ignore($this->work_location)

is for the route

Controller : create

public function store(StoreWorkLocationRequest $request)
{
  try {         
     $worklocation = HrWorkLocation::create([
        'location_name'     => $request->location_name,
        'is_active'         => 1,
     ]);

    Session::flash('success', 'Work Location is created successfully');
    return redirect()->route('hr.work_locations.index');
  } 
  catch (Exception $exception) 
  {
      Session::flash('error', 'Action failed!');
      return redirect()->route('hr.work_locations.index');  
   }        
  }

I observe that it allows location_name as England or england.

How do I make Rule::unique as case sensitive?

Thank you.

Upvotes: 3

Views: 6998

Answers (2)

PRAJIN PRAKASH
PRAJIN PRAKASH

Reputation: 1475

Add a custom validation to AppServiceProvider.php under the boot() method:

Validator::extend('iunique', function ($attribute, $value, $parameters, $validator) {
    $query = DB::table($parameters[0]);
    $column = $query->getGrammar()->wrap($parameters[1]);
    return ! $query->whereRaw("lower({$column}) = lower(?)", [$value])->count();
});

This can be extended further to accept the other parameters similar to the unique rule Now my $rules looks like this:

protected $rules = [
    'username' => 'required|alpha_dash|min:5|max:18|iunique:users,username',
];

see an issue reported here

Upvotes: 4

Makdous
Makdous

Reputation: 1433

You can make the input lower-cased so you don't have to worry of what the user input in the form.

use Illuminate\Support\Str;

After that, you can call it without the namespace prefix:

 Str::lower($request->location_name);

Upvotes: 0

Related Questions