Target Class Does Not Exist In Laravel 8


In this example we will learn about target class does not exist in laravel 8. In laravel 8 you can see there are many changes and updates. Many laravel users are facing issue in their new laravel 8 version when they try to load their routes in web.php and they run into an Exception that says something like "Target class [postController] does not exist".

You will get like IlluminateContractsContainerBindingResolutionException Target class does not exist, laravel target class does not exist, Target class AppHttpMiddlewareHandleInertiaRequests does not exist, Target class (PostController) does not exist, controller does not exist laravel 8.

So, let's see how to fix target class does not exist in laravel 8.

Upto Laravel 7, the RouteServiceProvider.php file had the below code:

here, namespace variable has stored 'App\Http\Controllers' and declered in middleware and prefix route as below.

protected $namespace = 'App\Http\Controllers';

protected function mapWebRoutes()
{
    Route::middleware('web')
        ->namespace($this->namespace)
        ->group(base_path('routes/web.php'));
}

protected function mapApiRoutes()
{
    Route::prefix('api')
        ->middleware('api')
        ->namespace($this->namespace)
        ->group(base_path('routes/api.php'));
}

But,In laravel 8 the $namespace variable was removed and the Route declaration changed as below:

 protected $namespace = null;

 public function boot()
    {
        $this->configureRateLimiting();

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

            Route::prefix('api')
                ->middleware('api')
                ->group(base_path('routes/api.php'));
        });
    }

 

 

So ,Here is 2 different solution for target Class Does Not Exist.

1) Add namespace manually

In this process you need to add value/path in $namespace variable and you need to declar in route as well like below.

protected $namespace = 'App\Http\Controllers';
   
    public function boot()
    {
        $this->configureRateLimiting();

        $this->routes(function () {
            Route::middleware('web')
            ->namespace($this->namespace)
            ->group(base_path('routes/web.php'));

            Route::prefix('api')
                ->middleware('api')
                ->namespace($this->namespace)
                ->group(base_path('routes/api.php'));
        });
    }

 Now run again your app all codes are working fine without "Target Class Does Not Exist" error

 

 

2) Using Full Namespace in your Routes

 In this solution you can use full namespace or changing all your route declarations like below code,

Route::resource('posts','App\Http\Controllers\PostController');

Here you need to add full path of your controller.

 


You might also like :

RECOMMENDED POSTS

FEATURE POSTS