Home > Software design >  Making a controller work from the non-standard directory in Laravel?
Making a controller work from the non-standard directory in Laravel?

Time:06-04

I'm creating a base code that will ultimately work for multiple sites. I managed to easily split it to support multiple "view" folders but I'm not sure how to do the same for controllers. This is the general structure:

/app/Http/Controllers     <--- standard controller folder
/resources/view           <--- standard view folders

This is the structure I want:

/sites/ASITE/view         <--- this I got working
/sites/ASITE/Controllers  <--- this I don't know how to get working

If I create a controller in /app/Http/Controllers and I create a route:

Route::get('/test', '\App\Http\Controllers\TestController@test')->name('Test');

Then it works fine if I call /test. But If I move it to "/sites/ASITE/Controllers" and change the namespace to:

sites\ASITE\Controllers;

And make the route:

Route::get('/test', '\sites\ASITE\TestController@test')->name('Test');

Then I get error "Target class [sites\ASITE\TestController] does not exist."

Any thoughts on how to get a controller to work from another folder?

CodePudding user response:

\App\Http\Controllers\TestController is not telling Laravel that TestController.php exists in App/Http/Controllers. It's saying that the TestController class is in the namespace App\Http\Controllers.

You'll have a line like this in TestController.php:

namespace App\Http\Controllers;

If you want to change the namespace, you'll need to do it there:

namespace sites\ASITE;

The reason the App namespace is available, and the sites namespace is not, is that you haven't defined the sites namespace in your composer.json:

"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "App\\": "app/",
        "sites\\": "sites/" <<< Add this line here
    }
},
  • Related