- Previous article phP-Laravel routing usage (detailed).
1. Create a controller
-
Where does the controller file go?
Save folder: app/Http/Controllers
-
How to name the controller file?
Naming: Use a large hump, and note the introduction of namespaces and base class controllers.
-
Command for creating a controller file
$PHP artisan make:controller Artisan make:controller Artisan make:controller (LoginController) $PHP artisan make:controller controller name (TestController) --r // If you need to put the controller in the specified directory // example: ` Http/app/Controllers/Admin ` $PHP artisan make: controller Admin/controller (LoginController)Copy the code
<? PHP // namespace App\Http\Controllers\Admin; Use Illuminate\Http\Request; use App\Http\Controllers\Controller; Class LoginController extends Controller {//Copy the code
Define methods in the routing access controller
-
Routing style
Route:: Request method (' URL ', anonymous function); Route:: Request method (' URL ', 'controller name @ operation method '); Route:: Request method (' URL ', 'command space/controller name @ operation method ');Copy the code
-
Create two controllers by using the Create Controller command
$artisan make:controller LoginController $artisan make:controller LoginController $artisan make:controller LoginController The Admin file needs to be manually created: $PHP artisan make:controller Admin/LogoutControllerCopy the code
-
The route binds the controller and calls the specified method in the web.php file:
Route::get('login', 'LoginController@index') -> name('login'); // If the controller class is in the Controllers root directory, Route::get('logout', 'Admin\LogoutController@index') -> name('logout');Copy the code
Note: the method parameters are the same as before
Route::get('login/{username? }', 'LoginController@index') -> name('login');Copy the code
Space grouping of routing commands
- Take the example above of exiting the login route
// If the controller class is in the Controllers root directory, Route::get('logout', 'Admin\LogoutController@index') -> name('logout'); Route::group(['namespace'=>'Admin'], function () {Route::get('logout', 'LogoutController@index') -> name('logout'); });Copy the code