laraveleloquent

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.

Solution

  • 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');