Last active
June 24, 2018 07:42
-
-
Save jarektkaczyk/6b3d41ae01d591302366c1246d8cc66f to your computer and use it in GitHub Desktop.
laravel multiformat response
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 | |
Response::macro('multiFormat', function ($data, $html = '') { | |
if (request('format') == 'json') { | |
return $this->json($data); | |
} | |
if (request('format') == 'xml') { | |
if (!is_array($data) && !$data instanceof Arrayable) { /* 400 Bad Request*/ } | |
$xml = (new ArrayToXml($data->toArray()))->toXml(); | |
return $this->make($xml, 200, ['Content-Type' => 'text/xml']); | |
} | |
if (request('format') == 'zip') { | |
if (!$data instanceof Compressable) { /* 400 Bad Request*/ } | |
return $this->download($data->toZipFile()); | |
} | |
return $html; | |
}); | |
// GET /podcasts/123 -> HTML | |
// GET /podcasts/123?format=json | |
// GET /podcasts/123?format=xml | |
// GET /podcasts/123?format=zip | |
Route::get('podcasts/{podcast}', function (Podcast $podcast) { | |
return Response::multiFormat( | |
$podcast, | |
view('podcasts', [ | |
'user' => Auth::user(), | |
'podcast' => $podcast, | |
]) | |
); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment