How to put controller inside folder in laravel 5.1

2019-07-08 08:05发布

I am new to laravel. I am trying to organise my controller by putting it inside a folder, but it doesn't seem to work.

My folder structure is like this:

/app
    /Http
        /Controllers
            /Admin
                ShowDashboard.php

My ShowDashboard.php file is like this:

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

use App\Http\Controllers\Controller;

class ShowDashboard extends Controller {

    /**
     * Show the profile for the given user.
     *
     * @param  int  $id
     * @return Response
     */
    public function init()
    {
        return 'Hi there!';
    }

}

My route is like this

Route::get('/admin', 'Admin\ShowDashboard@init');

When I tred to access http://localhost:8000/admin I get the following error:

Class App\Http\Controllers\Admin\ShowDashboard does not exist

My autolaoder section:

"autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    }

Am I missing something?

7条回答
Deceive 欺骗
2楼-- · 2019-07-08 08:49

Create a new controller in subfolder, for example: app/Http/Controllers/User/UserController.php

In this controller, at the end of namespace must include folder name

Like this: namespace App\Http\Controllers\User;

The important thing is under namespace must write use App\Http\Controllers\Controller;

finally in routes.php Route::get ( '/user', 'User\UserController@login' );

UserController.php contents:

<?php
namespace App\Http\Controllers\User;
use App\Http\Controllers\Controller;
class UserController extends Controller {
    public function login() {
        return 'this login';
    }
}

routes.php contents:

Route::get ( '/user/login', 'User\UserController@login' );

// or use this
Route::group ( [
        'namespace' => 'User'
], function () {
    Route::get ( '/user/login', 'UserController@login' );
} );
查看更多
登录 后发表回答