1. 程式人生 > 實用技巧 >laravel實現前後臺路由分離的方法

laravel實現前後臺路由分離的方法

當我們把路由寫到一個檔案中時,路由顯得雜亂不堪,不利於維護,這時我們需要將laravel路由進行分離

實現步驟:

1、首先在app/Https/Controlles/檔案下建立 Frontend(前端) Backend(後端) API(介面) 檔案

2、在app/Https/建立對應的路由檔案

3、開啟app/Providers/RouteServiceProvider.php 定義各個功能對應的路由檔案

程式碼如下:

<?php
 
namespace App\Providers;
 
use Illuminate\Routing\Router;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
 
class RouteServiceProvider extends ServiceProvider
{
 /**
 * This namespace is applied to the controller routes in your routes file.
 *
 * In addition, it is set as the URL generator's root namespace.
 *
 * @var string
 */
 protected $namespace = 'App\Http\Controllers';
 protected $backendNamespace;
 protected $frontendNamespace;
 protected $apiNamespace;
 protected $currentDomain;
 
 /**
 * Define your route model bindings, pattern filters, etc.
 *
 * @param \Illuminate\Routing\Router $router
 * @return void
 */
 public function boot(Router $router)
 {
 //
 $this->backendNamespace = 'App\Http\Controllers\Backend';
 $this->frontendNamespace = 'App\Http\Controllers\Frontend';
 $this->apiNamespace = 'App\Http\Controllers\API';
// $this->currentDomain = $this->app->request->server->get('HTTP_HOST');
 $this->currentDomain = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : "";
 
 parent::boot($router);
 }
 
 /**
 * Define the routes for the application.
 *
 * @param \Illuminate\Routing\Router $router
 * @return void
 */
 public function map(Router $router)
 {
// $router->group(['namespace' => $this->namespace], function ($router) {
//  require app_path('Http/routes.php');
// });
 
 $backendUrl = config('route.backend_url');
 $frontendUrl = config('route.frontend_url');
 $apiUrl = config('route.api_url');
 
 switch ($this->currentDomain) {
  case $apiUrl:
  // API路由
  $router->group([
   'domain' => $apiUrl,
   'namespace' => $this->apiNamespace],
   function ($router) {
   require app_path('Http/routes-api.php');
   }
  );
 
  break;
  case $backendUrl:
  // 後端路由
  $router->group([
   'domain' => $backendUrl,
   'namespace' => $this->backendNamespace],
   function ($router) {
   require app_path('Http/routes-backend.php');
   }
  );
  break;
  default:
  // 前端路由
  $router->group([
   'domain' => $frontendUrl,
   'namespace' => $this->frontendNamespace],
   function ($router) {
   require app_path('Http/routes-frontend.php');
   }
  );
 
  break;
 }
 
 }
}

此時只需要在不同的控制器中建立路由就 Ok了。

以上這篇laravel實現前後臺路由分離的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援碼農教程。