目标类不存在。Laravel 8 中的问题

7 php laravel laravel-8

使用 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']);
Run Code Online (Sandbox Code Playgroud)

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

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

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

目标类

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

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

所以我确实做到了。

Kam*_*aul 25

Laravel 8 更新写路由的方式

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

在 Laravel 8 中你需要使用像

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

或者

Route::get('/users', 'App\Http\Controllers\UserController@index');
Run Code Online (Sandbox Code Playgroud)

如果你想使用旧的方式

然后在 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'));
    });
}
Run Code Online (Sandbox Code Playgroud)

然后你可以使用像

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

或者

Route::get('/users', 'UserController@index');
Run Code Online (Sandbox Code Playgroud)