Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to create controllers under a subfolder in laravel 5

I have been struggling with this issue for the pas hour and I'm not sure what have I done wrong. So the case is like this. I wanted to create a controller folder go group different controllers into their groups. By default laravel projects created a controller folder structure like this

Http
--Controller
----Auth

So what I would like to do is to make something like this

Http
--Controller
----Auth
----Folder_a
----Folder_b
----Folder_c

After making my folders, the controllers in my folders are also properly namespaced like so

<?php namespace App\Http\Controllers\Folder_a;

    /*
    |--------------------------------------------------------------------------
    | Use the main controller to allow extend to the main controller
    |--------------------------------------------------------------------------

    */

    use App\Http\Controllers\Controller;

class SomethingController extends Controller {
        /* Do something here*/
}

And finally in my routes.php i call the actions like such

Route::get('/action1/', array('as' => 'action1', 'uses' => 'SomethingController@action1'));

But some how when i try to navigate to that site it gives me this error

ReflectionException in compiled.php line 1029:
Class App\Http\Controllers\SomethingController does not exist

Noticed that it still go into the default folder App\Http\Controllers\ to find the controller but if I do like this

Route::get('/action1/', array('as' => 'action1', 'uses' => 'Folder_a\SomethingController@action1'));

Then everything will be fine... What have I done wrong in this case? also i have tried composer dump-autoload, nothing has changed.

like image 450
Kenny Yap Avatar asked May 23 '15 13:05

Kenny Yap


People also ask

Which directory are controllers stored in Laravel?

In Laravel, a controller is in the 'app/Http/Controllers' directory. All the controllers, that are to be created, should be in this directory. We can create a controller using 'make:controller' Artisan command.

How do you make a resource controller in Laravel?

Creating the Controller This is the easy part. From the command line in the root directory of your Laravel project, type: php artisan make:controller sharkController --resource This will create our resource controller with all the methods we need.


1 Answers

You have done nothing wrong. This is the expected behavior! Laravel will search for the specified controller relative to App\Http\Controllers by default. So you have to specify the namespace from there. If you have many routes that lead to a controller in Folder_a you can use a route group to clean things up:

Route::group(['namespace' => 'Folder_a'], function(){
    Route::get('/action1/', array('as' => 'action1', 'uses' => 'SomethingController@action1'));
    // more routes
});
like image 71
lukasgeiter Avatar answered Oct 27 '22 11:10

lukasgeiter