2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Laravel8でTarget class does not exist が出る時

Last updated at Posted at 2020-09-16
web.php
    Route::group(['prefix' => 'test'], function() {
        Route::get('/','TestController@index');
    });

こんな感じでtestにアクセスし、indexアクションの処理をさせようとしたら、
Target class [TestController] does not existというエラーが発生したのでスペルミスなどを疑ってみましたが Laravel8では少し違う様です。

この人の記事を参考にしました。

英語は苦手なので解釈を間違えていたらすみません。

エラーの原因

RouteServiceProvider.php

            Route::middleware('web')
                ->group(base_path('routes/web.php'));

Laravel8ではこんな感じでApp\Providers\RouteServiceProvider.phpの中にある$namespace変数が削除されて宣言方法が変わった様なことを言ってる気がする。

解決方法は

RouteServiceProvider.php
protected $namespace = 'App\Http\Controllers';
//boot()の上で定義されている変数にこれを追加する
   public function boot()
   {
       
       $this->configureRateLimiting();
        
       $this->routes(function () {
           Route::middleware('web')
               ->namespace($this->namespace)//この行を追加
               ->group(base_path('routes/web.php'));
       });
   }

上記を追加してtestにアクセスするとしっかりとアクションの処理を呼び出せていました。

他の方法として

web.php
Route::get('path','App\Http\Controllers\YourController@index');

こんな感じで強引に書くのもありみたい。
他にも

web.php
use App\Http\Controllers\YourController;
Route::get('path', 'YourController@all');

Route::get('path', [YourController::class, 'all']);

こんな書き方もあるみたい。
コントローラーが少ない時は最後の3つでいいかもしれないけど規模が大きいとProvider.phpいじった方がいいのかも。

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?