問題描述
Laravel:8.x 目標類 [ArticlesController] 不存在 (Laravel:8.x Target class [ArticlesController] does not exist)
您好,我的代碼給了我這個錯誤:“目標類 [ArticlesController] 不存在。” 我試圖取消註釋“受保護的 $namespace = 'App\Http\Controllers';” 在 RouteServiceProvider 然後它說:“找不到類 'App\Http\Controllers\Article'”
ArticlesController:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ArticlesController extends Controller
{
public function index()
{
$articles = Article::latest()‑>get();
return view('articles.index', ['articles' => $articles]);
}
public function show($id)
{
$article = Article::find($id);
return view('articles.show', ['article' => $article]);
}
}
</code></pre>
Route:
Route::get('/', function () {
return view('welcome');
});
Route::get('/about', function () {
return view('about', [
'articles' => App\Models\Article::take(3)‑>latest()‑>get()
]);
});
Route::get('/articles', 'ArticlesController@index');
Route::get('/articles/{article}', 'ArticlesController@show');
</code></pre>
參考解法
方法 1:
Since Laravel 8 the route syntax has changed. You have to define the full path for controller class and specify the method.
use App\Http\Controllers\ArticlesController;
Route::get('/articles', [ArticlesController::class, 'index']);
Route::get('/articles/{article}', [ArticlesController::class, 'show']);
(by pro programmer、Anurat Chapanond)
參考文件