// Instead Of
$categories = Category::all();
$products = Products::all();
$products->each(function($product) use ($categories) {
$product->setRelation('category', $categories->where('id',$product->category_id));
});
// Do
$categories = Category::all();
$products = Products::all();
$products->setRelations(['category' => $categories]);
Created
March 4, 2020 23:42
-
-
Save ahmedash95/810606809d978eab79a43beaa4dde992 to your computer and use it in GitHub Desktop.
Laravel Eloquent Collection set relations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
Illuminate\Database\Eloquent\Collection::macro('setRelations',function(array $relations){ | |
$mappedRelation = []; | |
foreach($relations as $relationName => $relation) { | |
$mappedRelation[$relationName] = $relation->mapWithKeys(function ($model) { | |
return [$model->id => $model]; | |
}); | |
$this->each(function($item) use ($relationName,$mappedRelation){ | |
$property = "{$relationName}_id"; | |
$item->setRelation($relationName, $mappedRelation[$relationName][$item->{$property}]); | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment