使用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;
}
}
所以我做到了。
答案 0 :(得分:10)
参考链接https://laravel.com/docs/8.x/upgrade
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');