msslgomez
4 months ago
481
4
Laravel

When trying to create a item in foreach the item is not being created

Posted 4 months ago by msslgomez

I'm trying to do an import to the db and everything is working fine except when I try to create a group and group users, in the code what I'm doing is searching for a course and if the course exists then I add the course users (students) and I want to create a group also with the course users at the same time but the group part isn't working.

This is the code

DB::beginTransaction();
    foreach ($all as $a) {
        $item = array_values($a);

        $student = User::where('scard', $item[5])->first();
        $cname = str_replace('DescripciĆ³n del Curso:                       ', '', $item[3]);
        $course = Course::where('name', $cname)->first();

        //this isn't working, nothing gets added to the db
        if (!empty($course)) {
            $group = Group::where('name', $period . ' ' . $course->name . ' ' . $category->name)->first();
            if (empty($group)) {
                $group = new Group();
                $group->name = $period . ' ' . $course->name . ' ' . $category->name;
                $group->user_id = auth()->user()->id;
                $group->course_id = $course->id;
                $group->major_id = $course->major_id;
                $group->period_id = $id;
                $class = Classroom::where('name', $course->classroom)->pluck('id')->first();
                $group->classroom_id = $class;
                $group->save();
            }
        }

        if (!empty($student) && !empty($course)) {
            $assign = CourseUsers::where('course_id', $course->id)
                ->where('period_id', $id)
                ->where('user_id', $student->id)
                ->where('user_type_id', UserType::$STUDENT)
                ->first();
            if (empty($assign)) {
                $assign = new CourseUsers();
                $assign->course_id = $course->id;
                $assign->period_id = $id;
                $assign->user_id = $student->id;
                $assign->user_type_id = UserType::$STUDENT;
                $assign->save();
            }

            //this isn't working, nothing gets added to the db
            $guser = GroupUsers::where('category_id', $category->id)
                ->where('group_id', $group->id)
                ->where('user_id', $student->id)
                ->first();
            if (empty($guser)) {
                $guser = new GroupUsers();
                $guser->category_id = $category->id;
                $guser->group_id = $group->id;
                $guser->user_id = $student->id;
                $guser->save();
            }
        }
    }
    DB::commit();

Why is this happening? How can I fix it?

Please sign in or create an account to participate in this conversation.