Last active
February 17, 2017 23:04
-
-
Save mayoz/6dc1875053fdd862de0f3b846291aac1 to your computer and use it in GitHub Desktop.
Laravel collection macros
This file contains hidden or 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 | |
# 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() | |
{ | |
// | |
} | |
} |
This file contains hidden or 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 | |
# 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(); | |
}); | |
} |
This file contains hidden or 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 | |
# 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