Friday, March 17, 2017

How to avoid adding duplicate of element.Laravel, PHP

Shortly, there are teachers and i have to attach them courses. Every course should be added once only(not twice). My code is working but only for element with id=1.And the other courses can be attached to a teacher more than once. I am writing the code in laravel. (php). I can't uderstand why it is working only for the first element(course($id=1)). Can you help me please. Where is my mistake?? Thank You in advance. Here is my code. To One Teacher, many different courses should be attached. But not one course twice!

public function addCourse($id, Request $request) {
        $teacher = Teacher::findOrFail($id);
        if($teacher->has('courses')->where('id', $request->get('course_id'))->get()->isEmpty()) {
            $teacher->courses()->attach($request->get('course_id'));

        }
         else {
            flash()->error('This Course has been added already!')->important();
        }


        return back();
    }



via Ostonov Sherzod

Advertisement