Sunny
Sunny

Reputation: 14838

updating related tables from a controller laravel

Hi I’ve a users and education table. A user can have multiple school or college. So its one to many relationship. education table has school, from_year, to_year and user_id (fk) I want to update the user table as well as education table from a PUT request to users/{id} with email,school, from_year, and to_year fields.

// UsersController.php

   public function update(Request $request, $id)
    {
        $user = User::find($id);
        if (!$user) {
            return $this->respondNotFound('User not found');
        }
        $input = $request->all();
        $input = array_filter($input, 'strlen');
        //$user->update($input);
        //Get array of school records
        // $user->educatoion->push($records) // don't know what will come here to update the education table
        // or may be $user->push(); // don't know
        return $this->respond([
            'data' => $user,
        ]);
    }

Upvotes: 0

Views: 1419

Answers (1)

Jess Nielsen
Jess Nielsen

Reputation: 130

Try to keep it as simple as possible.

If this is your first time updating multiple tables at once, draw up a diagram of the process. This way you can identify the correct order of updates.

Take care to note any formatting that has to done on each value.

Laravel has some great functionality in regards to binding input to a model using ->update($data)

However, when binding to multiple models, you might run into issues with duplicate field names.

Update:

To create a education row from the $user model:

$education = new Education(array('school' => 'Harward', 'from_year' => 1999, 'to_year' => 2016));

User::find($id)->education()->save($education); 

Upvotes: 1

Related Questions