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?
Supposing you needed the eager-loaded relations previously (otherwise why eager-load at all?), you can:
unset($user->posts);
You can setRelations to empty array or use unset as mentioned.
But umm.. why would anyone do that?
Bcoz, I want to serialize this model without its relational data
@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.
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.
Thanks everyone for your co-operation
For anyone coming from Google, Laravel 5+ has a "fresh" method. So you can use this like:
$user = $user->fresh();
@alaminfirdows That will also reset the model with data from the database, meaning all other fields will be reset as well
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.
@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 sign in or create an account to participate in this conversation.