Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get relationships after insert

In my code, I insert a new row into the database:

$post = new Post;
$post->user_id = Auth::user()->id;
// more inserts
$post->save();

In my Post.php, I have:

protected $with = [
    'user', 'answers', 'questions'
];

public function users()
{
    return $this->belongsTo('App\User');
}

// etc

But when I return $post after I insert, there are no relationships (users, answers, questions) attached to it.

How can I get all of the default relationships to load after an insert?

like image 937
user6828106 Avatar asked May 15 '26 00:05

user6828106


2 Answers

The save() method persists the data to the database, but it doesn't do anything about refreshing the data on the Model or reloading relationships.

The easiest solution would be to refresh your object after calling save(). This will automatically eager load the relationships you've defined in your $with property on the model:

// ...
$post->save();

// refresh the post from the database
$post = $post->fresh();

Another option is to just manually reload the relationships yourself, using the load() method.

// ...
$post->save();

// reload the desired relationships
$post->load(['user', 'answers', 'questions']);

However, this duplicates the code that defines the relationships you'd like to be auto loaded (defined once in the Model, and then once in this code). You can mitigate that by creating a new function on your Model.

// in Post model
public function reloadRelations() {
    $this->load($this->with);
}

// code usage

// ...
$post->save();

// call your new function to reload the relations
$post->reloadRelations();

However, the only real benefit of going this route over just calling the built in fresh() method is that this won't re-run the query to get the original Post data.

If you're handling 1000s of requests a second, maybe the one query might make a difference, but other than that, I wouldn't worry about it, and just use the fresh() method. But, the options are here for you to choose.

like image 152
patricus Avatar answered May 17 '26 13:05

patricus


Instead of manually setting the attribute user_id, you should use the associate method from \Illuminate\Database\Eloquent\Relations\BelongsTo class.

$post->user()->associate(Auth::user());

// now you have the user inside your post.
dd($post->user);
like image 33
Rafael Berro Avatar answered May 17 '26 15:05

Rafael Berro



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!