使用 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
参考链接https://laravel.com/docs/8.x/upgrade
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)
| 归档时间: |
|
| 查看次数: |
21756 次 |
| 最近记录: |