【问题标题】:Laravel multiple routes file for apiLaravel 用于 api 的多个路由文件
【发布时间】:2017-12-07 11:50:51
【问题描述】:

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

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

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

  1. routes/admin.api.php 用于 Angular 应用程序

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

我已将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)

【问题讨论】:

标签: php laravel api routes laravel-5.4


【解决方案1】:
  1. 创建两个路由文件:admin.api.phpapp.api.php
  2. 编辑RouteServiceProvider.php文件如下:
    <?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');
            });
        }

    }

更多详情请见here

【讨论】:

  • 感谢您的宝贵时间,非常感谢,我已经更新了我的帖子,您能告诉我我缺少什么
猜你喜欢
  • 1970-01-01
  • 2017-05-03
  • 2020-01-20
  • 2016-03-14
  • 2019-04-24
  • 2020-08-02
  • 2019-08-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多