Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.6] Added unsetRelation method to Eloquent models #24486

Merged
merged 3 commits into from Jun 7, 2018
Merged

[5.6] Added unsetRelation method to Eloquent models #24486

merged 3 commits into from Jun 7, 2018

Conversation

IsraelOrtuno
Copy link
Contributor

There are many ways to set and load relationships in Eloquent models. However it becomes tricky for unsetting an already loaded relation.

I do work a lot in packages which interact with Eloquent and relationships with paradigms such as EAV and others where you have to manipulate relationships directly from traits. I think it'll be useful to provide as much methods as possible to manage them.

Right now, the only way I found to unset a relationship from outside the model was:

// Lets assume "user" and "image" relations and we try to remove "user"
$relations = $model->getRelations();
unset($relations['user']);
$model->setRelations($relations);

With this PR:

$model->unsetRelation('user');

*/
public function unsetRelation($relation)
{
if ($this->relationLoaded($relation)) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this necessary? As long as $this->relations isn't null, unset($this->relations('foo')) will always work

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are right, thought it could cause an undefined index error, will change

@laurencei
Copy link
Contributor

Out of curisosity - what is the use case for this? Why would you want to unset a relationship?

@IsraelOrtuno
Copy link
Contributor Author

This came up because I am developing a permalink based routing system. I am setting a Permalink model to the Route instance via a Macro method. When you cache your routes, you will get all these and their relationships encoded to base64. I do not want to cache anything else than the model itself, do not want to get a huge base64 string.

I guess this may be also useful for not serializing relations.

@taylorotwell taylorotwell merged commit 7538abb into laravel:5.6 Jun 7, 2018
@GrahamCampbell GrahamCampbell changed the title Added unsetRelation method to Eloquent models [5.6] Added unsetRelation method to Eloquent models Jun 7, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

4 participants