Laravel | three fields combination Valdiation - laravel

How to do a 3 fields combination validation?
I have this table merchant_product, the table has 4 columns :
id
merchant_id
product_id
branch_id
I don't want the same row duplicated like this when storing data.
Example :
id
merhcant_id
product_id
branch_id
1
1
1
1
2
1
1
1
I tried this approach but it seems not to work.
Here is my sample validation method :
$rules = [
'product_id' => ['required','unique:merchant_product,product_id,NULL,id,merchant_id,'.Auth::id()', new Varchar],
'merchant_id' => [new Varchar],
'branch_id' => ['required','unique:merchant_product,branch_id,NULL,id,merchant_id,'.Auth::id()', new Varchar],
];

You can use Rule::unique to validate both column together :
'product_id' => [
'required',
Rule::unique('merchant_product')->where(function ($query) use($request) {
return $query->where('product_id', $request->product_id)
->where('branch_id', $request->branch_id);
}),
],
Don't forget to add use Illuminate\Validation\Rule; on the top

Use firstOrCreate()
MerchantProduct::firstOrCreate([
'product_id' => $productId,
'merchant_id' => $merchantId,
'branch_id' => $brandId
]);
This will stop any duplicate record being created, using all 3 columns without doing extra processing with rules.
See the following article for usage:
https://laravel.com/docs/8.x/eloquent#retrieving-or-creating-models

Related

Laravel update specific data from model where it doesn't have array of ids

I want to update all model data except some from an array of ids, how is this kind of thing possible with eloquent?
What i'm doing:
Creating or updating events and setting availability to 0 also gatherings the ids in a foreach loop for each event
$rv = CalendarSchedule::updateOrCreate([
'date_start' => $import['start']->format('Y-m-d H:i:s'),
'date_end' => $import['end']->format('Y-m-d H:i:s'),
'operator_id' => $operator->id
],[
'location_id' => $operator->place_id,
'available' => 0,
'block' => 1
]);
array_push($ids, $rv->id);
Now when the foreach loop ends i want to update all the CalendarSchedule data except those in the ids array and set available => 1
Using made it work.
DB::table('calendar_schedules')->whereNotIn('id', $ids)->update([
'available' => 1
]);

How to increment column with Laravel Eloquent updateOrCreate()?

Is it possible to return the model id from the request below ?
Bar::insert([
'foo_id' => Foo::updateOrCreate([
'code' => $row[0],
'name' => $row[1]
])->increment('count')->id
]);
I also tried this:
Foo::updateOrCreate([
'code' => $row[0],
'name' => $row[1]
], [
'count' => DB::raw('count + 1')
])->id
But it doesn't work at inserting because it count is not yet set.
HINT: There is a column named "count" in table "foos", but it cannot be referenced from this part of the query. (SQL: insert into "public"."foos" ("id", "name", "count") values (123, Hello, count+1) returning "id")
=== EDIT ===
With DB::raw('IFNULL(count,0) + 1'), I'm getting:
SQLSTATE[42703]: Undefined column: 7 ERROR: column "count" does not exist
LINE 1: ... ("code", "name", "count") values ($1, $2, IFNULL(count,0) +...
^
HINT: There is a column named "count" in table "foos", but it cannot be referenced from this part of the query. (SQL: insert into "public"."foos" ("code", "name", "count") values (123, Hello, IFNULL(count,0) + 1) returning "id")
Unfortunately I don't think this is possible to reference the count column only when the update happens (since this is what is happening here). You will need to take the roundabout way:
$model = Foo::firstOrNew([
'code' => $row[0],
'name' => $row[1]
]);
$model->count = ($model->exists ? $model->count : 0) + 1;
$model->save();
Here $model->exists will be true if the model was retrieved from the database or false if a new one was created.
Efficiency-wise firstOrCreate is what updateOrCreate does anyway so there's no query cost added
try using IFNULL
Foo::updateOrCreate([
'code' => $row[0],
'name' => $row[1]
], [
'count' => DB::raw('IFNULL(count,0) + 1')
])
if you want the id, try it like this:
$id=(Foo::updateOrCreate([
'code' => $row[0],
'name' => $row[1]
], [
'count' => DB::raw('IFNULL(count,0) + 1')
]))->id;
note: this is working on mysql, not PostgreSQL
you just need to set column auto-increment in database and not need set it column in your eloquent

laravel 7 Validation unique multiple columns

how to viladate multiple columns
table name "exam_starts"
columns
id
exam_id
exam_multi_id
student_id
exam_class_id
exam_code_id
Status
class Student extends Model
{
// exam
public function exams(){
return $this->belongsToMany('App\Exam','exam_starts','student_id','exam_id')
->withPivot(['id','exam_multi_id','exam_class_id','exam_code_id','Attend','pass','Status'])-
>withTimestamps();
}
}
how to unique columns student_id and exam_class_id in table exam_starts ?
My Try in controller
class ExamClassController extends Controller
{
$this->validate($request, [
'exam_class_id' => [
'required',
'integer',
'unique:exam_startss,exam_class_id,'.$request->exam_class_id .',student_id' ,
],
'student_id' => 'bail|required|integer',
'exam_start_id' => 'bail|required|integer',
'exam_id' => 'bail|required|integer',
'exam_multi_id' => 'bail|required|integer',
'code' => 'nullable|string',
'student' => 'bail|required|string',
]);
}
this mysql resulte
(SQL: select count(*) as aggregate from `exam_starts` where `exam_class_id` = 1 and `student_id` <> 1)
Use Unique rule class and you can pass multiple wheres to it, to make an unique constraint that takes two columns.
(new Unique('exam_starts'))
->where('student_id ', $request->student_id)
->where('exam_class_id', $request->exam_class_id);
Set it into validation like so
'exam_class_id' => [
'required',
'integer',
(new Unique('exam_starts'))
->where('student_id ', $request->student_id)
->where('exam_class_id', $request->exam_class_id),
],

Update a 1 Row 1 Column with Multiple Values

i've some problem with my code.
$id = DB::table('sn_project_details')->insertGetId([
'emp_name' => $request->emp_name,
'emp_id' => $request->emp_id,
'department' => $request->department,
'submit_date' => $request->submit_date,
'total_amount' => $request->total_amount,
'project_tittle' => $request->project_tittle,
'project_desc' => $request->project_desc,
'scope' => $request->scope,
'file' => $request->file
]);
//Update Table
\DB::table('sn_project_details')
->where('project_id', $id)
->update(['doc_ref' => "ID_",$request->scope,"_",$id]);
return redirect('/user')
I want to update column doc_ref with example value ID_Scope_220,
ID_ its fixed value. Scope from textbox scope. 220 from #emp_id.
but when i execute this code, update query not working properly.
can someone help? thx
use dot instead of comma
->update(['doc_ref' => "ID_".$request->scope."_".$emp_id]);

Avoid duplication in doctor_id field with where clause in laravel 5.4

this is my doctors id
this is my user id
I can't insert anything when I put unique in the validation of doctor_id. When there's no unique it works fine.
I want to avoid duplicate doctor_id where auth::id == 1. Any advice is appreciated.
public function store(Request $request, $id)
{
$auth = Auth::id();
$constraints = [
'doctor_id' => 'required|unique',
'day1' => 'required|max:20',
'day2'=> 'required|max:60',
'day3' => 'required|max:60'
];
$input = [
'users_id' => $auth,
'doctor_id' => $id,
'day1' => $request['day1'],
'day2' => $request['day2'],
'day3' => $request['day3'],
'day4' => $request['day4'],
...
'day27' => $request['day27'],
'status' => '1'
];
$this->validate($request, $constraints);
Itinerary::create($input);
$added = array('added'=> 'Added Doctor to Itinerary Successful!!');
return redirect()->back()->with($added);
Have you tried this? (assuming your table is named itineraries):
'doctor_id' => 'unique:itineraries'
According to Laravel Doc, you should add the table name, and column name if possible:
unique:table,column,except,idColumn

Resources