Donald Donald
Donald Donald

Reputation: 67

Laravel foreach only getting first value

I am doing a peer marking system which requires a function that lecturer adds id list and when students enroll in a course, he enters his id needed to match the id on lecturer id list.

Controller

public function store(Request $request)
{
    $this->validate($request, [
        'course_code' => 'required',
        'studentid' => 'required'
    ]);

    $enrollment = new Enrollment;
    $enrollment->user_id = auth()->user()->id;
    $enrollment->course_id = $request->course;
    $enrollment->user_StudentID = $request->studentid;

    $input_course_id = $request->input('course_code');
    $input_studentid = $request->input('studentid');
    $course = Course::find($enrollment->course_id);

    $course_identifiers = $course->identifiers;

    // Need all the data in the database course table for comparison
    //$course represents the contents of the course table in all databases, then you need to loop first, then judge
    //$course stands for list $signleCourse for each piece of data

    foreach ($course_identifiers as $course_identifier) {
        //              if ($course_identifier->studentid == $input_studentid )
        if ($input_studentid == $course_identifier->studentid) {
            if ($request->course == $input_course_id) {
                //if true,save and redirect
                $enrollment->save();
                return redirect('/enrollment')->with('success', 'Course Enrolled');
            } else {
                return redirect('/enrollment')->with('error', 'Please Enter Correct Confirmation Code');
                //If false do nothing
            }
        } else {
            return redirect('/enrollment')->with('error', 'Please Enter Correct Student ID');
            //If false do nothing
        }
    }
}

It can only match the first value, but other values I enter cannot be recognized.

Upvotes: 0

Views: 145

Answers (1)

Drewster
Drewster

Reputation: 539

Turn off your redirects. It's really hard to understand the context of that code but it looks like if it fails to match it redirects so doesn't go through the second and subsequent values of $course_identifiers.

Upvotes: 1

Related Questions