Laravel Controller Subfolder routing

后端 未结 14 1421
一生所求
一生所求 2020-11-29 16:44

I\'m new to Laravel. To try and keep my app organized I would like to put my controllers into subfolders of the controller folder.

controllers\\
---- folder1         


        
相关标签:
14条回答
  • 2020-11-29 17:40

    1.create your subfolder just like followings:

    app
    ----controllers
    --------admin
    --------home
    

    2.configure your code in app/routes.php

    <?php
    // index
    Route::get('/', 'Home\HomeController@index');
    
    // admin/test
    Route::group(
        array('prefix' => 'admin'), 
        function() {
            Route::get('test', 'Admin\IndexController@index');
        }
    );
    ?>
    

    3.write sth in app/controllers/admin/IndexController.php, eg:

    <?php
    namespace Admin;
    
    class IndexController extends \BaseController {
    
        public function index()
        {
            return "admin.home";
        }
    }
    ?>
    

    4.access your site,eg:localhost/admin/test you'll see "admin.home" on the page

    ps: Please ignore my poor English

    0 讨论(0)
  • 2020-11-29 17:43

    I think to keep controllers for Admin and Front in separate folders, the namespace will work well.

    Please look on the below Laravel directory structure, that works fine for me.

    app
    --Http
    ----Controllers
    ------Admin
    --------DashboardController.php
    ------Front
    --------HomeController.php
    

    The routes in "routes/web.php" file would be as below

    /* All the Front-end controllers routes will work under Front namespace */
    
    Route::group(['namespace' => 'Front'], function () {
        Route::get('/home', 'HomeController@index');
    });
    

    And for Admin section, it will look like

    /* All the admin routes will go under Admin namespace */
    /* All the admin routes will required authentication, 
       so an middleware auth also applied in admin namespace */
    
    Route::group(['namespace' => 'Admin'], function () {
        Route::group(['middleware' => ['auth']], function() {            
            Route::get('/', ['as' => 'home', 'uses' => 'DashboardController@index']);                                   
        });
    });
    

    Hope this helps!!

    0 讨论(0)
提交回复
热议问题