Skip to content

Instantly share code, notes, and snippets.

@ahmedash95
Created March 4, 2020 23:42
Show Gist options
  • Save ahmedash95/810606809d978eab79a43beaa4dde992 to your computer and use it in GitHub Desktop.
Save ahmedash95/810606809d978eab79a43beaa4dde992 to your computer and use it in GitHub Desktop.
Laravel Eloquent Collection set relations

Usage

// 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]);
<?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