Ad
Laravel Unique Department For Each Company
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
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS - Conditionally Load a Different Page
- → Make a Laravel collection into angular array (octobercms)
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?
- → Validating fileupload(image Dimensions) in Backend Octobercms
- → OctoberCMS Fileupload completely destroys my backend
- → How do I call the value from another backed page form and use it on a component in OctoberCms
Ad