定义Laravel 8路由的名称空间 [英] Defining a namespace for Laravel 8 routes

查看:35
本文介绍了定义Laravel 8路由的名称空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关Laravel 8.x中路由的问题

Question about routing in Laravel 8.x

现在,我在web.php文件中添加了以下行:

Now Im adding such lines in web.php file:

use App\Http\Controllers\FirstController;
use App\Http\Controllers\SecondController;
use App\Http\Controllers\ThirdController;

,然后仅在 FirstController :: class 等上工作.

在开始时仅使用 namespace App \ Http \ Controllers; 而不是所有 use 行一次又一次x是错误的吗?

Is it wrong to use just namespace App\Http\Controllers; instead of all use lines one after another x times at the beggining?

谢谢.

推荐答案

相反,我只是在 app/Providers/RouteServiceProvider.php 中取消注释此行,它将恢复为Laravel< 8使用 App \ Http \ Controllers 命名空间在'routes/web.php' 'routes/api.php'中自动添加路由声明的行为

Instead, I would simply uncomment this line in app/Providers/RouteServiceProvider.php which will revert back to the Laravel <8 behavior of automatically prefixing route declarations in 'routes/web.php' 'routes/api.php' with the App\Http\Controllers namespace.

/**
 * The controller namespace for the application.
 *
 * When present, controller route declarations will automatically be prefixed with this namespace.
 *
 * @var string|null
 */
 protected $namespace = 'App\\Http\\Controllers';

如果您是在首次发布v8时创建项目的,则此注释掉的属性可能不在您的 app/Providers/RouteServiceProvider.php 中(似乎已将其删除,然后又添加回去),如果没有,那么添加它并取消Commnet,并确保它在prop的 boot 方法中使用,并且可以正常工作.

This commented out property might not be in your app/Providers/RouteServiceProvider.php if you created the project when v8 was first released, (seems it was removed then added back) if not, just add it and uncommnet, and make sure its used in the boot method the prop and it'll work.

public function boot()
{
    $this->configureRateLimiting();

    $this->routes(function () {
        Route::prefix('api')
            ->middleware('api')
            ->namespace($this->namespace)           // make sure this is present
            ->group(base_path('routes/api.php'));

        Route::middleware('web')
            ->namespace($this->namespace)            // make sure this is present
            ->group(base_path('routes/web.php'));
    });
}

这篇关于定义Laravel 8路由的名称空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆