加载控制器 HomeController 时发生错误,提示:Target class [HomeController] does not exist.

来源:3-2 Laravel路由

AlanHwi

2021-05-15

访问 http://laravel.test/home/hello 时,加载控制器 HomeController 发生错误(备注:访问http://laravel.test/home 是可以正常显示的)
错误提示:
Illuminate\Contracts\Container\BindingResolutionException
Target class [HomeController] does not exist.
图片描述

写回答

2回答

AlanHwi

提问者

2021-05-15

已经通过搜索引擎找的答案了,错误原因总结:

因为我现在使用的是Laravel8.36.2,所以这里的绑定方式与Laravel7.x以前的版本不同。

在Laravel7.x中路由指向控制器使用的是如下: 

Route::get('home/hello', 'HomeController@hello');

而从Laravel8开始使用标准的PHP调用语法

如要设置./Controllers/HomeController.php控制器下hello()方法的路由

//首先在/routes/web.php引入

use App\Http\Controllers\HomeController;

//创建路由 http://laravel.test/home/hello

Route::get('/home/hello', [HomeController::class, 'home']);

2
1
marong126
感谢 AlanHwi, 只是视频中方法的名称是 'hello', 而不是 'home' 如果改成: Route::get('/home/hello', [HomeController::class, 'hello']); 就不会出错了
2021-06-20
共1条回复

AlanHwi

提问者

2021-05-15

其他的错误截图这个页面上传不了,我复制的一些错误提示如下:

Illuminate\Container\Container::build

vendor/laravel/framework/src/Illuminate/Container/Container.php:835

     * @throws \Illuminate\Contracts\Container\BindingResolutionException

     * @throws \Illuminate\Contracts\Container\CircularDependencyException

     */

    public function build($concrete)

    {

        // If the concrete type is actually a Closure, we will just execute it and


        // hand back the results of the functions, which allows functions to be


        // used as resolvers for more fine-tuned resolution of these objects.


        if ($concrete instanceof Closure) {

            return $concrete($this, $this->getLastParameterOverride());

        }

        try {

            $reflector = new ReflectionClass($concrete);


        } catch (ReflectionException $e) {


            throw new BindingResolutionException("Target class [$concrete] does not exist.", 0, $e);

        }

        // If the type is not instantiable, the developer is attempting to resolve


        // an abstract type such as an Interface or Abstract Class and there is


        // no binding registered for the abstractions so we need to bail out.


        if (! $reflector->isInstantiable()) {


            return $this->notInstantiable($concrete);

        }

        // if (in_array($concrete, $this->buildStack)) {


        //     throw new CircularDependencyException("Circular dependency detected while resolving [{$concrete}].");


        // }

        $this->buildStack[] = $concrete;


 


0
0

Laravel重构企业级电商项目 从根源解决重构难题

一门专注于提升大型复杂项目重构能力的课程

423 学习 · 149 问题

查看课程