Explain in detail the simple method of API version control through routing in laravel 5.6


Laravel version: 5.6

With the iteration of API, the new version often needs to inherit the functions of the old version and modify and extend the original functions. At this time, in order to be compatible with the interfaces of various versions, version control is required.

Request version differentiation:

Attach version information to the request header, such as app version: 1.0.1

Acquisition method of laravel:


File path:

For usercontroller version 1.0.1, the file path is

Version 1.0.2, which is

Note that if the original functions of 1.0.1 need to be used in version 1.0.2, the original classes need to be inherited

use App\Http\Controllers\Api\UserController as UserCtrl;
class UserController extends UserCtrl

version control

Version resolution method:

function getRouteContoller($controllerName)
  $base_path = 'App\Http\Controllers\Api\\';
  //No version
  $app_version = Request::header('app-version');
  if (!$app_version) return $controllerName;
  //Current version
  $version_path = 'v' . str_replace('.', 'd', $app_version) . '\\';
  $controllerPath = $base_path . $version_path . $controllerName;
  if (class_exists($controllerPath)) {
    return $version_path . $controllerName;
  //Previous versions
  $versionNumbers = intval(str_replace('.', '', $app_version));
  for ($i = $versionNumbers - 1; $i > 0; $i--) {
    $version_path = 'v' . implode('d', str_split($i)) . '\\';
    $controllerPath = $base_path . $version_path . $controllerName;
    if (class_exists($controllerPath)) {
      return $version_path . $controllerName;
  return $controllerName;

Note: this method will resolve version 1.0.2 to v1d0d2, and judge whether the corresponding class exists. If so, it will directly return the path of the class; If it does not exist, look down for the existence of the 1.0.1 version class until the existing class is found and returned.

Routing file

Route::post('login', getRouteContoller('UserController').'login');

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support developpaer.

Recommended Today

Tpextbuilder – displays [component] – use of with method

Series articles: Background development framework based on (tp5.1, tp6.0) (design ideas refer to laravel admin) Tpextbuilder – hasbuilder (encapsulating page) Tpextbuilder – form Tpextbuilder – Search Tpextbuilder – table Tpextbuilder – selectpage drop-down data Tpextbuilder – left tree navigation Tpextbuilder – displays [component] – field Tpextbuilder – displays [component] – when form linkage Tpextbuilder – […]