当我们在路由中调用控制器ProductController时,会发现以下问题: "Target class [ProductController] does not exist"
你也可以看到下面的截图。
实际上这不是错误,但是laravel 8从RouteServiceProvider.php文件中删除了默认名称空间。
我们可以在路由文件中指定,也可以在RouteServiceProvider.php文件中定义默认名称空间。让我们一一看这两种解决方案。
解决方案1:在路由文件中使用
routes/web.php
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\ProductController; use App\Http\Controllers\PostController; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('welcome'); }); Route::resource('products', ProductController::class); Route::get('posts', [PostController::class, 'index']);
解决方案2:在RouteserviceProvider 中定义
第二种解决方案是您可以将laravel定义为旧版本。所以让我们将其定义为:app/Http/Providers/RouteServiceProvider.php
<?php namespace App\Providers; use Illuminate\Cache\RateLimiting\Limit; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; use Illuminate\Http\Request; use Illuminate\Support\Facades\RateLimiter; use Illuminate\Support\Facades\Route; class RouteServiceProvider extends ServiceProvider { /** * The path to the "home" route for your application. * * This is used by Laravel authentication to redirect users after login. * * @var string */ public const HOME = '/home'; protected $namespace = 'App\Http\Controllers'; /** * Define your route model bindings, pattern filters, etc. * * @return void */ public function boot() { $this->configureRateLimiting(); $this->routes(function () { Route::middleware('web') ->namespace($this->namespace) ->group(base_path('routes/web.php')); Route::prefix('api') ->middleware('api') ->group(base_path('routes/api.php')); }); } ....
routes/web.php
<?php use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('welcome'); }); Route::resource('products', 'ProductController'); Route::get('posts', 'PostController@index');
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦