Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create an instance of a model with a relationship?

I create a model instance to add a record to the DB, and after using the save() function I pass the added object to the DB for further processing, but I can't get data from the added record via the connection? Is this possible? Or should I re-download the row from the DB?

The code looks something like this

...
$model_2 = new Model2();
$model_2->name=$user->name;
$model_2->age=$user->age;
$model_2->category_id=$user->category_id; // here is the link to the table "categories";
$model_2->save();
dd($model_2);  // The data has been entered but the "relationships" field is empty.
like image 636
Studlara Avatar asked Dec 19 '25 15:12

Studlara


1 Answers

You should be able to load the relationship once you've saved your model, using lazy eager loading. So if your relationship is named category, you would do this:

$model_2->load('category');
like image 58
aynber Avatar answered Dec 21 '25 11:12

aynber



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!