11

当使用 laravel 8 创建一个新项目时,我得到了这个错误。

Illuminate\Contracts\Container\BindingResolutionException 目标类 [SayhelloController] 不存在。http://127.0.0.1:8000/users/john

<?php
    
use Illuminate\Support\Facades\Route;
     
Route::get('/', function () {
    return view('welcome');
});  
    
Route::get('/users/{name?}' , [SayhelloController::class,'index']);

在 laravel 文档中,Routes 控制器类必须像这样定义

 // Using PHP callable syntax...
Route::get('/users', [UserController::class, 'index']);

// Using string syntax...
Route::get('/users', 'App\Http\Controllers\UserController@index');

目标类

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class SayhelloController extends Controller
{
    public function index($name = null)
    {
        return 'Hello '.$name;
    }
}

所以我确实做到了。

4

1 回答 1

33

Laravel 8 更新写路由的方式

参考链接https://laravel.com/docs/8.x/upgrade

在 laravel 8 你需要使用 like

use App\Http\Controllers\SayhelloController;
Route::get('/users/{name?}' , [SayhelloController::class,'index']);

或者

Route::get('/users', 'App\Http\Controllers\UserController@index');

如果你想使用旧的方式

然后在RouteServiceProvider.php

添加这一行

 /**
     * This namespace is applied to your controller routes.
     *
     * In addition, it is set as the URL generator's root namespace.
     *
     * @var string
     */
    protected $namespace = 'App\Http\Controllers'; // need to add in Laravel 8
    

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

    $this->routes(function () {
        Route::prefix('api')
            ->middleware('api')
            ->namespace($this->namespace) // need to add in Laravel 8
            ->group(base_path('routes/api.php'));

        Route::middleware('web')
            ->namespace($this->namespace) // need to add in Laravel 8
            ->group(base_path('routes/web.php'));
    });
}

然后你可以使用喜欢

Route::get('/users/{name?}' , [SayhelloController::class,'index']);
Route::resource('/users' , SayhelloController::class);

或者

Route::get('/users', 'UserController@index');
于 2020-09-14T09:59:32.063 回答