vendredi 2 novembre 2018

Laravel update several records in a loop

In a Laravel 5 application I have a controller method for creating packages of items:

public function store(Request $request)
{
    $package = new Package;
    $package->title = $request->input('title');
    $package->description = $request->input('description');

    $package->save();

    $package_id = DB::table('package')->where('title', $package->title)->pluck('Id');

    foreach($request->course as $key) {

        $course_name = DB::table('course')->where('Id', $key)->pluck('name');

        $data = array('Package_Id' => $package_id[0], 'Course_Id' => $key, 'University_Id' => $home_university_id[0], 
        'Package_title' => $package->title, 'Course_name' => $course_name[0], 'Pu_Id' => $partner_university_id);
        Course_package::insert($data);    
    }

    return redirect('home/package');

}

The store method works fine. Looping the different courses from an array, since the user can add an arbitrary number of courses to each package works fine during creation. The problem is updating the packages. Running a similar method for updating each package but cannot figure out how to update the courses that are looped in to the DB from the store method.

Update method:

public function update(Request $request, $id)
{
    $package = Package::find($id);
    $package->title = $request->input('title');
    $package->save();

    $package_id = DB::table('package')->where('title', $package->title)->pluck('Id');

    foreach($request->course as $key) {

        $course_name = DB::table('course')->where('Id', $key)->pluck('name');

        $data = array('Package_Id' => $package_id[0], 'Course_Id' => $key, 'University_Id' => $home_university_id[0], 
        'Package_title' => $package->title, 'Course_name' => $course_name[0], 'Pu_Id' => $partner_university_id);

        Course_package::insert($data);  
    }

    return redirect('home/package');
}

I understand that I cannot run the same code as in the create method inserting a $data array to the Course_package table. But I am a bit confused on how to update records that have been changed by the user coming with $request->course which is an array.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2qojli7
via IFTTT

Aucun commentaire:

Enregistrer un commentaire