Bukhari
Bukhari

Reputation: 151

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();
    }

Upvotes: 2

Views: 152

Answers (3)

Bukhari
Bukhari

Reputation: 151

PROBLEM SOLVED. I used

$teacher->courses()->sync([$request->get('course_id')],$detaching = false);

Finally i have this script:

> public function addCourse($id, Request $request) {
>         $teacher = Teacher::findOrFail($id);
>         $teacher->courses()->sync([$request->get('course_id')],$detaching =
> false);
>         
>         return back();
>     }

Thank you all.

Upvotes: 1

EddyTheDove
EddyTheDove

Reputation: 13259

To attach a one to many

$teacher = Teacher::findOrFail($id);
$course = Course::findOrFail($request->get('course_id'));

$course->teacher()->associate($teacher);;
$course->save();

Upvotes: 0

user1669496
user1669496

Reputation: 33068

I believe there is an issue in how you are querying.

When you do this...

$teacher->has('courses')->where('id', $request->get('course_id'))

That ->where() is still looking at the teachers table, not the courses table. I think what you really want to do is use a whereHas to determine if the teacher has that course.

$hasCourse = Teacher::whereHas('courses', function($q) use ($request) {
    // Here we can add constraints on the courses table
    $q->where('id', $request->get('course_id'));
})->where('id', $id)->exists();

if (! $hasCourse) {
    $course = Course::findOrFail($request->get('course_id'));
    $course->teacher()->associate($id);
}

Upvotes: 1

Related Questions