Created
April 24, 2018 11:42
-
-
Save sydgren/602a424246dd95cdbca36d44b05b0e4f to your computer and use it in GitHub Desktop.
Laravel API versioning using the Accept-Version header
This file contains hidden or 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 | |
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); | |
} | |
} |
This file contains hidden or 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 | |
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); | |
} | |
} |
This file contains hidden or 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 | |
return [ | |
'version' => 'v1', | |
]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment