Skip to content

Instantly share code, notes, and snippets.

@sydgren
Created April 24, 2018 11:42
Show Gist options
  • Save sydgren/602a424246dd95cdbca36d44b05b0e4f to your computer and use it in GitHub Desktop.
Save sydgren/602a424246dd95cdbca36d44b05b0e4f to your computer and use it in GitHub Desktop.
Laravel API versioning using the Accept-Version header
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller as BaseController;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
abstract class Controller extends BaseController
{
protected $realClass;
public function __construct()
{
$this->realClass = sprintf(
'%s%s\\%s',
rtrim(__CLASS__, class_basename($this)),
studly_case(config('api.version')),
class_basename($this)
);
}
public function __call($method, $parameters)
{
if (! class_exists($this->realClass)) {
throw new NotFoundHttpException;
}
if (! method_exists($this->realClass, $method)) {
throw new NotFoundHttpException;
}
return app()->call(sprintf('%s@%s', $this->realClass, $method), $parameters);
}
}
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Request;
class ApiVersion
{
public function handle(Request $request, $next)
{
if ($version = $request->header('Accept-Version')) {
config(['api.version' => $version]);
}
return $next($request);
}
}
<?php
return [
'version' => 'v1',
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment