Laravel Orm Not Save Relation Key And Child Model

- 1 answer

I would like to save data through Eloquent, in particular an Object and its respective Address. The Object has inside an id_address which should be updated following the creation of the Address. But this does not happen. Although it is following the guide code and the mapping of the relationships in the models is correct.

That's the code in my controller Object:

$obj= new Object(['alias' => $curr['alias']]);
$address= new Address(['address'=>$curr['address']['city']]);

relation in models Object:

public $belongsTo = [
        'address' => [

relation in address model:

public $hasOne = [
        'obj' => [

Why is created only the object and not the address and the id_address in object table?



$address= new Address(['address'=>$curr['address']['city']]);

This will instantiate an Address object, but it will not save in db. So that object doesn't have an id and that's why the id_address (btw I strongly suggest you to change the field name to address_id) is not updated.

You should do

$address= new Address(['address'=>$curr['address']['city']]);

Anyway it doesn't make sense to save your Object twice, just save it after the associate() call.