Reputation: 2372
I've a fetch a Laravel Eloquent collection by:
$product = Product::query()->with(['merchant', 'picture'])->where('id', $id)->first();
and get the dump of $product
is
Product {
#casts: ...
#dates: ...
#connection: "mysql"
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:1 [
"id" => 27
]
#original: ...
#changes: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: array:2 [
"merchant" => Merchant {...}
"picture" => Picture {...}
}
]
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
#guarded: ...
}
I need to unset the relation object merchant
and picture
from this collection.
I've tried following options but failed:
unset($product['merchant']);
unset($product->merchant);
Any help will be appreciate.
Thanks in advance
Upvotes: 35
Views: 35151
Reputation: 3869
Note that I had an issue with unsetRelation('polymorphicRelation')
and unsetRelations()
when using a polymorphic relationship (Laravel 10).
I was able to remove "classic" relationships from my hydrated model, but no matter how I tried to remove the morphed relationship, I would always end with it in my serialized object (toArray()
).
unsetRelations()
would remove all but my polymorphic one, and unsetRelation('polymorphicRelation')
did nothing on the polymorphic. But both worked perfectly with a belongsTo relation also eager loaded/hydrated.
I could fix this using:
$model->unsetRelation('polymorphicRelation')->setHidden(['polymorphicRelation'])->toArray()
. (not sure that the unsetRelation
is really useful in this case.
The "Before that" option of Jonas Staudenmeir may also work in this case.
Upvotes: 1
Reputation: 11
withoutEagerLoads()
Worked for me here is an eample:
$observations = Observation::selectRaw('COUNT(*) as count, DATE(created_at) as date')
->whereIn('tenant_id', $tenant_ids)
->whereBetween('created_at', $timelines[$request->timeline])
->groupBy('date')
->withoutEagerLoads()
->get();
Upvotes: 0
Reputation: 25906
In Laravel 5.6.25, you can use unsetRelation()
:
$product->unsetRelation('merchant')->unsetRelation('picture');
Before that:
$relations = $product->getRelations();
unset($relations['merchant'], $relations['picture']);
$product->setRelations($relations);
Upvotes: 58
Reputation: 1379
I have to tables with the same fields.. So I need to check the different column based on value. So if the value of foreign key is same then need to unset that relation
If you have merchant
property in the model (merchant
column in the table) you can get it value using $product->getOriginal('merchant')
or $product->getAttribute('merchant')
Upvotes: 2