Skip to content

Instantly share code, notes, and snippets.

@jonpemby
Forked from adamwathan/1-add-macros.php
Created March 28, 2018 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonpemby/60c64b6bd6beac9cfca56667b2dae4ff to your computer and use it in GitHub Desktop.
Save jonpemby/60c64b6bd6beac9cfca56667b2dae4ff to your computer and use it in GitHub Desktop.
Multiformat Endpoints in Laravel
<?php
namespace App\Providers;
use Illuminate\Http\Request;
use Illuminate\Routing\Route;
use Illuminate\Support\ServiceProvider;
use App\Http\Middleware\CaptureRequestExtension;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Route::macro('multiformat', function () {
return $this->setUri($this->uri() . '.{_format?}');
});
Request::macro('match', function ($responses, $defaultFormat = 'html') {
if ($this->route('_format') === null) {
return value(array_get($responses, $this->format($defaultFormat)));
}
return value(array_get($responses, $this->route('_format'), function () {
abort(404);
}));
});
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
<?php
/**
* Mark a route as 'multiformat' to allow different extensions (html, json, xml, etc.)
*
* This route will match all of these requests:
* /podcasts/4
* /podcasts/4.json
* /podcasts/4.html
* /podcasts/4.zip
*/
Route::get('/podcasts/{id}', 'PodcastsController@show')->multiformat();
/**
* Use `Request::match()` to return the right response for the requested format.
*
* Supports closures to avoid doing unnecessary work, and returns 404 if the
* requested format is not supported.
*
* Will also take into account the `Accept` header if no extension is provided.
*/
class PodcastsController
{
public function show($id)
{
$podcast = Podcast::findOrFail($id);
return request()->match([
'html' => view('podcasts.show', [
'podcast' => $podcast,
'episodes' => $podcast->recentEpisodes(5),
]),
'json' => $podcast,
'xml' => function () use ($podcast) {
return response($podcast->toXml(), 200, ['Content-Type' => 'text/xml']);
}
]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment