Skip to content

Instantly share code, notes, and snippets.

@mayoz
Last active February 17, 2017 23:04
Show Gist options
  • Save mayoz/6dc1875053fdd862de0f3b846291aac1 to your computer and use it in GitHub Desktop.
Save mayoz/6dc1875053fdd862de0f3b846291aac1 to your computer and use it in GitHub Desktop.
Laravel collection macros
<?php
# app/Providers/AppServiceProvider.php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
require base_path('macros/collection.php');
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
<?php
# macros/collection.php
use Illuminate\Support\Collection;
if (! Collection::hasMacro('toHierarchy')) {
/*
* Get the collection of items as a hierarchical array.
*
* @param string $foreign
* @param string $primary
* @param mixed $value
* @return \Illuminate\Support\Collection
*/
Collection::macro('toHierarchy', function ($foreign = 'parent_id', $primary = 'id', $value = null) {
return $this->where($foreign, $value)
->map(function ($parent) use ($foreign, $primary) {
return data_set($parent, 'children', $this->toHierarchy(
$foreign, $primary, data_get($parent, $primary)
));
})
->values();
});
}
<?php
# routes/web.php
use App\Category;
Route::get('/', function () {
return Category::get()->sortBy('position')->toHierarchy();
});
/*
Category table structure
---
id
parent_id
title
position
created_at
updated_at
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment