【问题标题】:Problems with Laravel Controller classLaravel 控制器类的问题
【发布时间】:2021-10-24 18:26:27
【问题描述】:

我知道这个问题已经被问过好几次了,但没有一个答案对我有用,所以我再次问这个问题。

我正在尝试在 Laravel 中创建一个小网站,并创建了一个路由和一个控制器,但是当我尝试在 url 中访问它时,我收到了这个错误:

Illuminate\Contracts\Container\BindingResolutionException
Target class [Admin\PlanController] does not exist.

这是我的web.php

use Illuminate\Support\Facades\Route;


Route::get('admin/plans', 'Admin\PlanController@index')->name('plans.index');

Route::get('/', function () {
    return view('welcome');
});

这是我的PlanController.php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class PlanController extends Controller
{
    public function index(){
        return view('admin.pages.plans.index');
    }
}

如果有任何帮助,这里是我的RouteServiceProvider.php

    protected $namespace = 'App\\Http\\Controllers';

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

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

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

【问题讨论】:

  • 您缺少我认为的默认命名空间。你可以添加你的路线吗? Laravel 8?
  • 确保您使用正确的name plans.index 访问您的anchor 标签

标签: php laravel routes


【解决方案1】:

如果您使用的是 Laravel 8,最好使用新的路由语法,如下所示:

use App\Http\Controllers\Admin\PlanController;

Route::get('/admin/plans', [PlanController::class, 'index'])->name('plans.index');

确保控制器在正确的目录app/Http/Controllers/Admin

【讨论】:

  • 感谢您的评论,但它不起作用:/同样的错误
  • 你清除路由缓存了吗? php artisan route:cache
  • 是的,同时使用route:cacheroute:clear。我还运行了命令composer dump autoload
【解决方案2】:

您的代码似乎一切正常。确认与控制器的目录必须是

app\Http\Controllers\Admin

或进行更改

$this->routes(function () {
        Route::middleware('web')
            ->namespace('App\Http\Controllers')
            ->group(base_path('routes/web.php'));

不使用在此处获取命名空间值作为RouteServiceProvider.php 中的变量。

【讨论】:

    【解决方案3】:

    您可以在路由中描述完整的命名空间;

    Route::get('admin/plans','App\Http\Controllers\Admin\PlanController@index')->name('plans.index');
    

    【讨论】:

      猜你喜欢
      • 2013-11-14
      • 1970-01-01
      • 2014-04-26
      • 2019-11-26
      • 2019-06-13
      • 2020-06-22
      • 2018-09-25
      • 2017-02-25
      • 2013-05-28
      相关资源
      最近更新 更多