nahid's avatar
Level 1

Is there any way to unload model loaded relation

Suppose I retrieve this data

$user = User::with(['posts'])->find(1);

After retrieving this, I want to unload posts relation from this Model.

Is there any way?

0 likes
11 replies
tykus's avatar

Supposing you needed the eager-loaded relations previously (otherwise why eager-load at all?), you can:

unset($user->posts);
crnkovic's avatar

You can setRelations to empty array or use unset as mentioned.

But umm.. why would anyone do that?

nahid's avatar
Level 1

Bcoz, I want to serialize this model without its relational data

amitshahc's avatar

@staudenmeir is this available in lumen 8.0?

I am getting method not exists. before/after ->get()

in app.php the $app->withFacades(); and $app->withEloquent(); are uncommented already.

tykus's avatar

From experience, I would suggest that you separate the serialization (presentation) of your models from the models themselves. Look at API Resources or Transformers as a means of representing the serialized User (and other models) rather than adding/removing/showing/hiding properties on the model itself.

1 like
nahid's avatar
Level 1

Thanks everyone for your co-operation

alaminfirdows's avatar

For anyone coming from Google, Laravel 5+ has a "fresh" method. So you can use this like:

$user = $user->fresh();

Sinnbeck's avatar

@alaminfirdows That will also reset the model with data from the database, meaning all other fields will be reset as well

amitshahc's avatar

I have an extension of this question. How can we unload the nested default relationship?

e.g. Project has one => Staff model has one => protected $with = ['user']; defined inside the Staff model.

but when we want to fetch the Project with Staff and don't want the user attached to it.

Redtama's avatar

@amitshahc I think the way you would do this is by constraining the eager load:

$project = Project::with(['staff' => function (Builder $query) {
    $query->without('user');
}])->get();

This should retrieve all projects with their staff relation loaded but each staff will not load their user relation.

Please or to participate in this conversation.