Ad

Laravel Namespaced Routes Not Found

- 1 answer

I have a routes file like this:

<?php

Route::group(['prefix' => 'project1', 'namespace' => '\App\Project1\Controllers'], function()
{

    Route::get('/', '[email protected]');
});

But when I try to access dev.api/project1/, it will throw an error of:

Class App\Http\Controllers\App\Project1\Controllers\UsersController does not exist

You may point out that it's obvious, you should do something like:

Route::get('/', '\App\Project1\Controllers\[email protected]');

But isn't it useless to declare the namespace without being to actually use it in the first place?

Anyways, what should I do to be able to to call the controllers without prepending the namespace every single time? Thanks

Ad

Answer

By default, the routes in app/Http/routes.php are automatically loaded inside the App\Http\Controllers namespace. Inside this file, any namespace you specify will be relative to that parent namespace.

If you would like to modify this behavior, this can be done in the app/Providers/RouteServiceProvider.php file.

A couple quick options:

  • You could modify the default parent namespace by modifying the protected $namespace attribute.

  • You could get rid of any default parent namespace by removing the initial $router->group() inside the map() method.

  • You could create a brand new app/Project1/routes.php file, and load it inside a second router group, with your App\Project1\Controllers as the default parent namespace for any route listed in that file:

    public function map(Router $router)
    {
        $router->group(['namespace' => $this->namespace], function ($router)     {
            require app_path('Http/routes.php');
        });
        $router->group(['namespace' => 'App\Project1\Controllers'], function ($router)     {
            require app_path('Project1/routes.php');
        });
    }
    
Ad
source: stackoverflow.com
Ad