Skip to content

Instantly share code, notes, and snippets.

@jarektkaczyk
Last active June 24, 2018 07:42
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jarektkaczyk/6b3d41ae01d591302366c1246d8cc66f to your computer and use it in GitHub Desktop.
Save jarektkaczyk/6b3d41ae01d591302366c1246d8cc66f to your computer and use it in GitHub Desktop.
laravel multiformat response
<?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