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

时间:2020-09-14 09:53:54

标签: 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']);

在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;
    }
}

所以我做到了。

1 个答案:

答案 0 :(得分:10)

Laravel 8更新了编写路由的方式

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

在laravel 8中,您需要使用

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');