Abdul Hadi
Abdul Hadi

Reputation: 1

Trying to Insert data into DB with IF statement and foreach loop

This insertion code is for assigning "Subjects to the Class". My controller is ok, web.php is ok, and I have cross-checked my model and database table. But I don't know why this code is not working for insertion. When I remove the IF statement and foreach loop, then it works. Otherwise, it does not show a success message and goes to the next page.

public function insert(Request $request)
{
    if (!empty($request->subject_id)) {
        foreach ($request->subject_id as $subject_id) {
            $save = new ClassSubjectModel;
            $save->class_id = $request->class_id;
            $save->subject_id = $subject_id;
            $save->status = $request->status;
            $save->created_by = Auth::user()->id;
            $save->save();
        }

        return view ('admin/assign_subject/list')->with('success', "Subject Successfully Assigned to Class");
    } else {
        return redirect()->back()->with('error', 'No subject selected. Please try again.');
    }
}

Upvotes: 0

Views: 68

Answers (0)

Related Questions