Spread the love

Target class controller does not exist in laravel 8 or laravel 9 error encounters in laravel versions above 8 because Before laravel 8 we can call controller without full namespace but after laravel 8, laravel team has changed the way to call the controller class. In laravel 5 and 6 we can call without specify the namespace but in laravel 8 and 9 you either need to call full namespace or you can import the class as follow

Route::get('/articles', 'App\Http\Controllers\ArticleController@index');

And another way is to assign the namespace in group as follow


Route::group(["namespace"=>"\App\Http\Controllers"],function(){
    Route::get('articles3', 'ArticleController@showArticle');
});

In this way way we created a group of routes using route group method and assigned the namespace.

we can also include controller and then can call method of it directly as follow

<?php
use App\Http\Controllers\ArticleController;
use Illuminate\Support\Facades\Route;

Route::get('/articles', [ArticleController::class,"index"]);

Here index is the method name and ArticleController::class is the name of controller class which use as use App\Http\Controllers\ArticleController;

Laravel has changed the way to call the routes in laravel 8 and laravel. if you used the previous way to call the controller then it will throw error like Target class controller does not exist since in laravel 8 or 9 it is required to define the namespace.

So to overcome from this exception of Target class controller does not exist in laravel 8 or laravel 9 we need to call it above way.

Last method if you want the same behavior as laravel 5, laravel 6 and laravel 7 then you can open the app/Providers/RouteServiceProvider.php class and uncomment the protected $namespace = 'App\\Http\\Controllers'; as follow

<?php

namespace App\Providers;

use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;

class RouteServiceProvider extends ServiceProvider
{
    ... 
    protected $namespace = 'App\\Http\\Controllers';

    ...
}

I hope this will help you a lot to resolve the issue of Target class controller does not exist in laravel 8 or Laravel 9

You can also read : What is Laravel 8 middleware ?

Leave a Reply