Laravel - Inserting & Updating Related Models

Asked

Viewed 124 times

1

in the Laravel documentation it teaches how to do Insert on related models. Here is an example of how to do it in the documentation: Inserting & Updating Related Models

$comment = new App\Comment(['message' => 'A new comment.']);    
$post = App\Post::find(1);    
$post->comments()->save($comment);

In all the documentation examples he does the find($id) before saving the data to Model related, that’s how I did:

$person = new Person;
$person->name = $request->input('name');
$person->cpf = $request->input('cpf');
$person->save();

$person = Person::find($person->id);

foreach ($request->input('phone') as $phone){
    $phones[] = new PersonPhone(['phone' => $phone]);
}
$person->phone()->saveMany($phones);

The table person has a relationship of hasMany with the table person_phone. The method phone() returns this relationship:

return $this->hasMany('App\Models\Person\PersonPhone','id_person', 'id');

Is there any way I can put everything in the bank without saving and then find? I’ve searched all of Laravel’s documentation and here at Stackoverflow and found nothing.

  • 2

    Just take the find line because in this case it is unnecessary, because after save() you already have the Person object if save() returns true

1 answer

0


As you have already made an object and called the method save() returning true if the data is saved line after with find is not necessary because you already have one Person that needs, modification:

$person = new Person;
$person->name = $request->input('name');
$person->cpf = $request->input('cpf');
$person->save();
if ($person) // se for verdade que salvou os dados retorna true
{
    foreach ($request->input('phone') as $phone){
        $phones[] = new PersonPhone(['phone' => $phone]);
    }
    $person->phone()->saveMany($phones);
}

Remembering that when you need to work with the relations of a Model, it needs to somehow be present in some variable, is that in your case missed if notice that you already had and do not need to call again.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.