23
votes

I am using Laravel 6.0 and I try to list all my routes with artisan route:list, but it fails and returns:

Illuminate\Contracts\Container\BindingResolutionException : Target class [App\Http\Controllers\SessionsController] does not exist.

at /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Container/Container.php:806 802| 803| try { 804| $reflector = new ReflectionClass($concrete); 805| } catch (ReflectionException $e) { > 806| throw new BindingResolutionException("Target class [$concrete] does not exist.", 0, $e); 807| } 808| 809| // If the type is not instantiable, the developer is attempting to resolve 810| // an abstract type such as an Interface or Abstract Class and there is

Exception trace:

1 Illuminate\Foundation\Console\RouteListCommand::Illuminate\Foundation\Console{closure}(Object(Illuminate\Routing\Route)) [internal]:0

2 ReflectionException::("Class App\Http\Controllers\SessionsController does not exist") /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Container/Container.php:804

3 ReflectionClass::__construct("App\Http\Controllers\SessionsController") /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Container/Container.php:804

Up to now I just have a very simple web.php routes file:

Route::get('/', function () {
    return view('index');
});


Route::prefix('app')->group(function () {
    // Registration routes
    Route::get('registration/create', 'RegistrationController@create')->name('app-registration-form');
});


// Templates
Route::get('templates/ubold/{any}', 'UboldController@index');

Any idea how I could debug this issue?

20
Did you make sure to run php artisan config:cache?mukesh kumar
Do you have any SessionsController?Prafulla Kumar Sahu
Shame on me. I thought I created the SessionsController, but I didn't. After creating it and running php artisan config:cache it works. Thanks a lot for the quick response!Andreas
It could also be the namespace at the top of your controllerRobert Rocha

20 Answers

22
votes

Run this command

  php artisan config:cache 
68
votes

I was upgrading from Laravel 7 to Laravel 8 (Laravel 8 is still a few days in development) and also had this issue.

The solution was to use a classname representation of the controller in the route:

So in web.php instead of

Route::get('registration/create', 'RegistrationController@create')

it is now:

Solution 1: Classname representation

use App\Http\Controllers\RegistrationController;

Route::get('/', [RegistrationController::class, 'create']);

Solution 2: String syntax

or as a string syntax (full namespaces controller name):

Route::get('/', 'App\Http\Controllers\RegistrationController@create');

Solution 3: Return to previous behaviour

As this should issue should only happen if you upgrade your application by creating a brand new laravel project you can also just add the default namespace to the RouteServiceProvider:

app/Providers/RouteServiceProvider.php

class RouteServiceProvider extends ServiceProvider
{
    /* ... */
     
    /** ADD THIS PROPERTY
     * If specified, this namespace is automatically applied to your controller routes.
     *
     * In addition, it is set as the URL generator's root namespace.
     *
     * @var string
     */
    protected $namespace = 'App\Http\Controllers';

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        $this->configureRateLimiting();

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

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

    /* ... /*
}

See also https://laravel.com/docs/8.x/routing#basic-routing or https://laravel.com/docs/8.x/upgrade (search for "Routing").

38
votes

For those who have similar issue with Illuminate\Contracts\Container\BindingResolutionException : Target class [<className>] does not exist. message, this also could be helpful:

composer dump-autoload
4
votes

In my case it was solved by running

php artisan optimize:clear
php artisan config:cache

The optimize:clearcommands clears everything

3
votes

In my case it was a matter of Linux's file name case sensitivity. For a file named IndexController, having Indexcontroller will work in windows but not in Linux

2
votes

In my case same error occurred because of forward slash / but it should be backward slash \ in defining route,

it happens when you have controller in folder like as in my case controller was in api Folder, so always use backward slash \ while mentioning controller name.

see example:

Error-prone code:

Route::apiResource('categories', 'api/CategoryController');

Solution code:

Route::apiResource('categories', 'api\CategoryController');
2
votes

on Larave 7 I had the same issue.

I checked the spelling of the controller name.

I recognize I have the wrong spelling in the "AlbumContoller" and I rename it to "AlbumController". so I forgot "r"

after I renamed the file and controller name and controller name in the web.php

Route::resource('albums', 'AlbumsController');

everything worked well

So You Don't need these two:

1- use App\Http\Controllers\IndexContoller;

2- Route::get('/', [MyModelController::class, 'myFunction']);

2
votes

This is the perfect answer, I think:

  • Option 1:
use App\Http\Controllers\HomepageController;
Route::get('/', [HomepageController::class, 'index']);
  • Option 2:
Route::get('/', 'App\Http\Controllers\HomepageController@index');
2
votes

Simply add the following line in app->Providers->RouteServiceProvider.php

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

Alright i got similar problem, i was trying to be smart so i wrote this in my web.php

Route::group([
    'middleware'    => '', // Removing this made everything work
    'as'            => 'admin.',
    'prefix'        => 'admin',
    'namespace'     => 'Admin',
],function(){

});

All i had to do is just to remove all the unnecessary/unused option from group. That's all.

1
votes

try to correct your controller name

my route was

Route::get('/lien/{id}','liensControler@show');

and my controller was

class liensController extends Controller
{
  // all the methods of controller goes here.
}
1
votes

I did all these

1: php artisan config:cache

2: checked for controller name spellings.

3: composer dump-autoload

4: Just changed the forward / slash to backward \ in route.

4th one worked for me.

1
votes

Now You Can use controller outside controller folder

use App\Http\submit;

Route::get('/', [submit::class, 'index']);

Now my controller excited in http folder

You have to change in controller file something

<?php

namespace App\Http;

use Illuminate\Http\Request;
use Illuminate\Http\Controllers\Controller;
class submit extends Controller {
    public function index(Request $req) {
        return $req;
    }
}
1
votes

I am running Laravel 8.x on my pc. This error gave me headache. To recreate the error, this is what I did: First I created a controller called MyModelController.php Secondly, I wrote a simple function to return a blade file containing 'Hello World', called myFunction. Lastly, I created a Route: Route::get('/','MyModelController@myFunction'); This did not work.

This was how I solved it. First you would have to read the documentation on: (https://laravel.com/docs/8.x/releases#laravel-8)

At the 'web.php' file this was the Route i wrote to make it work:

use App\Http\Controllers\MyModelController;

Route::get('/', [MyModelController::class, 'myFunction']);

1
votes

you have to specify full path to the class

Previously it was

Route::get('/wel','Welcome@index');

Now it has changed to

use App\Http\Controllers\Welcome;
Route::get('wel',[Welcome::class,'index']);
0
votes

I had this problem while leaving an empty middleware class in my middleware groups by mistake :

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:100,1',
            'bindings',
            'localization',
            '' // Was empty by mistake
        ],
    ];
0
votes

replace-

Route::resource('/admin/UserOff','admin/UsersController');

with-

Route::resource('/admin/UserOff','admin\UsersController');

forward / with \

0
votes

I had the same problem but with a middleware controller. So finally I linked that middleware in kerner.php file. It is located at app\Http\Kernel.php

I have added this line in route middleware.
'authpostmanweb' => \App\Http\Middleware\AuthPostmanWeb::class

  protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        'authpostmanweb' => \App\Http\Middleware\AuthPostmanWeb::class
    ];
0
votes

You can define a route to this controller action like so:

use App\Http\Controllers\UserController;

Route::get('user/{id}', [UserController::class, 'show']);

0
votes

just check web.php and see lower and upper case letters