Laravel多个路由文件为api

时间:2017-07-04 06:40:49

标签: php laravel api routes laravel-5.4

我正在为2个客户端应用程序,移动应用程序和angular2管理面板开发API。

如果我在一个默认的routes/api.php中编写两个应用程序的路由,这将是非常巨大的。

所以,我想将api routes文件拆分为:

    对于角度应用
  1. routes/admin.api.php

  2. 移动应用
  3. routes/app.api.php

  4. 我修改了RouteServiceProvide,如下所示

    <?php
    
    namespace App\Providers;
    
    use Illuminate\Support\Facades\Route;
    use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
    
    class RouteServiceProvider extends ServiceProvider
    {
        protected $namespace = 'App\Http\Controllers';
    
        public function boot()
        {
            //
    
            parent::boot();
        }
    
        public function map()
        {
            $this->mapAdminApiRoutes();
    
            $this->mapApiRoutes();
    
            $this->mapWebRoutes();
    
            //
        }
    
        protected function mapWebRoutes()
        {
            Route::middleware('web')
                 ->namespace($this->namespace)
                 ->group(base_path('routes/web.php'));
        }
    
        protected function mapApiRoutes()
        {
            Route::prefix('api/v1')
                 ->middleware('api')
                 ->namespace($this->namespace)
                 ->group(base_path('routes/api.php'));
        }
    
        protected function mapAdminApiRoutes()
        {
            Route::prefix('api/v1')
                 ->middleware('api')
                 ->namespace($this->namespace)
                 ->group(base_path('routes/admin.api.php'));
        }
    }
    

    我收到以下错误

    (1/1) FatalErrorException
    Illuminate\Routing\Router::loadRoutes(): Failed opening required 'D:\Workspace\Project Izzmart\izzmart\routes/api.php' (include_path='.;C:\php\pear')
    in Router.php (line 329)
    

1 个答案:

答案 0 :(得分:1)

  1. 创建两个路径文件:admin.api.phpapp.api.php

  2. 编辑RouteServiceProvider.php文件,如下所示:

  3. &#13;
    &#13;
    <?php
    
    namespace App\Providers;
    
    use Illuminate\Support\Facades\Route;
    
    
    class RouteServiceProvider extends ServiceProvider
    {
        protected $namespace = 'App\Http\Controllers';
        protected $apiNamespace = 'App\Http\Controllers\Api\v1';
    
        public function boot()
        {
    
            parent::boot();
        }
    
        public function map(Router $router) {
            $router->group(['namespace' => $this->namespace], function ($router) {
                require app_path('Http/routes/web.php');
            });
            $router->group(['namespace' => $this->apiNamespace], function ($router) {
                require app_path('Http/api.php');
            });
            $router->group(['namespace' => $this->apiNamespace], function ($router) {
                require app_path('Http/admin.api.php');
            });
        }
    
    }
    &#13;
    &#13;
    &#13;

    有关详细信息,请参阅here