Laravel API – Archive nested collection group by year, month, day

Assuming you have a Photo model than belongs to a Gallery model.

You also have set the Dingo plugin and your routes.php file has the following:

$api->get( 'photos/archive/{year}/{month}/{day}', 'PhotosController@getArchive' );
$api->get( 'photos/archive/{year}/{month}', 'PhotosController@getArchive' );
$api->get( 'photos/archive/{year}/', 'PhotosController@getArchive' );
$api->get( 'photos/archive', 'PhotosController@getArchive' );

Let’s say you want to have a grouped collection by year/month/day for your photos (based on created date) like this:

[year] => {

	[month] => {
	
		[day] => [

			item[1],
			item[2],
			...
			item[N],
		]
		
	}
	
}

You can also find the from and to datetimes using:

$from = Carbon::createFromDate( 2016)->startOfYear()->toDateTimeString();
$to   = Carbon::createFromDate( 2016 )->endOfYear()->toDateTimeString();
$range = [ $from, $to ];

With all that, Laravel made it easy !

$result = Photo::with( 'gallery' )
   ->whereBetween( 'created_at', $range )
   ->orderBy( 'created_at', 'desc' )
   ->get()
   ->groupBy( function ( $item ) {
	   return $item->created_at->format( 'Y' );
   } )
   ->map( function ( $item ) {
	   return $item->groupBy( function ( $item ) {
		   return $item->created_at->format( 'm' );
	   } )->map( function ( $item ) {
		   return $item->groupBy( function ( $item ) {
			   return $item->created_at->format( 'Y-m-d' );
		   } );
	   } );
   } );

VOILA

laravel api archive group by dates