How to use the correct updateOrcreate in Laravel?

Published 1 week ago by nero

How to use the correct updateOrcreate in Laravel?

I want to add and change data in the same code. I've been using updateOrcreate but the results are not as desirable.

The code can only change the data, but can not change the data.

My table:

jobs:

    id
    title
    deskription

educations:

    id
    name

job_educations:

    id
    job_id
    education_id

Here's my code snippet:

    public function update(Request $request, $id)
      {                
        $input = Input::all();
        $edu=$input ['education'];
            for($i=0;$i<count($edu);$i++){
                JobEducation::updateOrCreate(
                    [
                            'job_id'=>$id, 
                     ],
                     [
                         'job_id'=>$id,                
                            'education_id' => $edu[$i]                   
                    ]
             );
    }

My requirement: I want to change the existing data and add new data.

Can anyone fix my code?

lanatel

It is not the best idea to use updateOrCreate() in this case. First of all, your job_educations table doesn't need id column. Secondly, you can define a many to many relation https://laravel.com/docs/5.6/eloquent-relationships#many-to-many between your jobs and educations tables. Thus, you don't need a JobEducation model at all. And then, with this relation you can use sync() or if you don't want to delete existing records syncWithoutDetaching() method. https://laravel.com/docs/5.6/eloquent-relationships#updating-many-to-many-relationships

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