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 vue3+electron打包获取本地视频属性,文件夹里面有ffprobe.exe 文件还会报错这是什么原因呢?
  • ¥20 用51单片机控制急停。
  • ¥15 孟德尔随机化结果不一致
  • ¥15 在使用pyecharts时出现问题
  • ¥15 深度学习残差模块模型
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信