LoginSignup
0
0

More than 1 year has passed since last update.

ルーティングで'Target class [hoge] does not exist.'と怒られたときの対処法

Posted at

Laravel Framework 9.22.1
マニュアルに沿い、Controllerを作成し、indexというアクションを追加、web.phpにルーティングを設定したら表記のエラーで怒られました。

最初にやった

make:controller コマンドでHelloControllerを作成
サンプルのアクションを記述し、ルート情報を設定したところ、表記のエラーに。

web.php
Route::get('hello', 'HelloController@index');

ためした①

エラーメッセージで検索したところ、Laravel 8以降からルーティングの書き方が変わっているとのことで、Route::get の表記を修正。
参考:https://teratail.com/questions/292482#reply-413765

web.php
Route::get('hello', [HelloController::class, 'index']);

→エラー解消せず!!:joy:

ためした②

さらにLaravel ⑧以降のルーティングの注意点として、

ルート定義ファイル web.php の冒頭にルート定義で使用されているコントローラの名前空間をuseキーワードを使用して書く

とのこと。
参考:https://qiita.com/Masahiro111/items/6c9cde6c265a241439c4

追加したコントローラの名前空間を冒頭に追記。

web.php
<?php

use Illuminate\Support\Facades\Route;
+ use App\Http\Controllers\HelloController;

→うごいた!!:joy:
image.png

※念のため「ためした①」で直したRoute設定を修正前に戻し、「ためした②」の名前空間の追記はそのままにしてテストしてもエラーが出た

まとめ

Laravel 8以降からルーティングの設定のしかたと、ルート定義のお作法が変わっている

  • Routeの設定を以下の形式にすること
web.php
Route::get('ページ名', [コントローラ名::class, 'アクション名']);
  • web.phpの冒頭に使用したいコントローラの名前空間をuseキーワードを使用して書くこと
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0