douliaodan2738 2017-08-04 08:20
浏览 95
已采纳

具有命名空间的Laravel Api Route失败

i have a small crud frontend to store information. The frontend controller is called ShowsController. And i want to get alle Shows from the api.

So my routes/web.php contains:

Route::resource('shows', 'ShowsController');

Thats perfect and worked really well.

My routes/api.php contains:

Route::resource('shows', 'ShowsController', ['only' => ['index']]);

The route /api/shows should give me the shows as json. to decide frontend and api i put the ShowsController into Controllers/Api folder

The Controllers/Api/ShowsController contains:

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Show;

class ShowsController extends Controller
{
    public function index(){
        return response()
            ->json(Show::all())->withHeaders([
                'Content-Type' => 'text/json',
                'Access-Control-Allow-Origin' => '*'
            ]);
    }
}

And i also changed the RouteServiceProvider to:

protected function mapApiRoutes()
{
    Route::group([
        'middleware' => 'api',
        'namespace' => 'Api',
        'prefix' => 'api',
    ], function ($router) {
        require base_path('routes/api.php');
    });
}

But the command php artisan route:list gives me an exception:

[ReflectionException]
Class Api\ShowsController does not exist

Why is laravel not finding the defined ShowsController in the api directory?

  • 写回答

1条回答 默认 最新

  • doucong4535 2017-08-04 08:25
    关注

    I don't know what version of Laravel you are using, but in 5.4, I have, by default, this method:

    protected function mapApiRoutes()
    {
        Route::prefix('api')
             ->middleware('api')
             ->namespace($this->namespace)
             ->group(base_path('routes/api.php'));
    }
    

    It could work if you replace namespace($this->namespace) by namespace($this->namespace . '\Api').

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题