Ad

Laravel Unique Department For Each Company

- 1 answer

I have a table named departments where 2 columns 1. name 2. company, I want to apply validation on name for single company.

 public function store(Request $request)
 {
    $company = Auth::user()->company_id;
    $this->validate($request, [
        'company'=>'unique:departments,company',
    ]);

    $department = Department::create([
        'name' => $request->name,
        'company' => $request->company,
    ]);
  }

expected result of departments is

name      company
======================
Accounts    1
Purchase    1
Accounts    2
Sales       2
Accounts    2  //wrong i want validation here
Purchase    1  //wrong i want validation here
Ad

Answer

This is the format of unique validation unique:table,column,except,idColumn details https://laravel.com/docs/5.6/validation#rule-unique. And with adding additional where condition it will be like this unique:table,column,except,idColumn,anotherColumn,anotherColumnValue

Add validation on department name

public function store(Request $request)
{
    //If getting company from request 
    $company = $request->company;

    //if getting company from auth user
    $company = Auth::user()->company_id;

    $request->validate([
        'name' => 'required|max:255|unique:departments,name,NULL,id,company,'. $company
    ]);

    $department = Department::create([
        'name' => $request->name,
        'company' => $company,
    ]);
}

Note: Better if you change the company column name to company_id in department because you are storing company id in it.

Ad
source: stackoverflow.com
Ad