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.
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
– novic