Skip to content
Advertisement

Laravel 7 Eloquent: Method refresh() on a model ignores default (nested) eager loading

I’m saving/updating a model and use the refresh() method to output the new data.

The Laravel documentation says:

If you plan on accessing the relationship after using the save or saveMany methods, you may wish to use the refresh method to reload the model and its relationships

Controller

  public function store()
  {
    //
    $comic = new Comic;
    $comic->fill($this->validateComic());
    $comic->save();
    return $comic->refresh();
  }

  public function update(Comic $comic)
  {
    //
    $comic->fill($this->validateComic());
    $comic->save();
    return $comic->refresh();
  }

Model

In the Comic model i defined default eager loadings:

  protected $with = ['series', 'series.publisher'];

This works perfect for a simple GET method. But if i save the model and use refresh() on it, the output loses its relationships.

Also the behaviour is different for the store()- and the update()-methods. The store()-method gives me no relationship. The update()-method returns only the series relationship (but not the nested one).

Is this a bug or am i missing something in the documentation?

Thanks.

Example data

{
"comic_id":21,
"series_id":5,
"comic_issue":"2",
"comic_name":"Test after 6",
"status_id":1,
"comic_rating":null,
"comic_release_date":"2015-09-26",
"comic_read_date":null,
"comic_summary":"Summary 5",
"created_at":"2020-08-07T17:28:14.000000Z",
"updated_at":"2020-08-08T17:14:16.000000Z",
"series":
    {
    "series_id":5,
    "series_name":"Assumenda consectetur.",
    "publisher_id":4,
    "release_date":null,
    "publisher":
        {
        "publisher_id":4,
        "publisher_name":"Aliquam earum."
        }
    }
}

Advertisement

Answer

This is actually expected for how refresh works. refresh only reloads the relationships that were already loaded. In the first example there were no relationships loaded as that model wasn’t retrieved from the database, it is a brand new model instance you directly created. The second example is most likely a Route Model Binding where the model has been returned from the database and because you are using the protected $with it was loaded with those relationships, so it has those relationships reloaded.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement