??
How validate unique combination?
i have pivot table course_subject, in this table combination of "course_id, subject_id" are primary key, so how can i validate unique key combination before attaching key here is my controller
public function postform(Request $request)
{
// $this->validate($request,[
// 'course_id' + 'subject_id' => 'required|unique:course_subject',
// ]);
$courses = $request->course_id;
$subjects = $request->subject_id;
$course = Course::where('id',$courses)->first();
$subject = Subject::where('id',$subjects)->first();
$course->psubjects()->attach($subject);
flash()->success('Successfully Subject Added in Course '. $course->name);
return back();
}
migration table
Schema::create('course_subject', function (Blueprint $table) {
$table->integer('course_id')->unsigned()->index();
$table->integer('subject_id')->unsigned()->index();
$table->primary(['course_id','subject_id']);
$table->timestamps();
});
Okay, in your validation something like this should work:
$this->validate($request, [
'course_id' => 'required|unique:course_subject, course_id, NULL, NULL, subject_id, ' . $request['subject_id'],
'subject_id' => 'required|unique:course_subject, subject_id, NULL, NULL, course_id, ' . $request['course_id'],
]);
When the first check is done it's only done for defined value of subject_id (you have subject_id=x in your DB and it checks course_id uniqueness for it). Same with the next line, it checks subject_id uniqueness for course_id = x.
I'm only not sure about the NULL, NULL. Tell me if it works.
You might want to check course_id and subject_id for SQL injection before checking uniqueness.
Please or to participate in this conversation.