Get the App
SLTechnology News&Howtos  ›  Development  › 

How to create Controller in Laravel

Shulou Source: shulou.com Published: 2022-06-02 07:47:12 09月14日 Update

This article is about how to create controllers in Laravel. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

To replace all request processing logic defined as closures in the routing file, if you want to use control classes to organize these behaviors, the controller can organize the relevant request processing logic into a separate class, and the controller is stored in the app/Http/Controllers directory.

First, simply create a controller

/ / use the php artisan command to automatically load the namespace after creation, and automatically base controller base class php artisan make:controller [controller path /] controller name

Second, the classification of controllers

1. Basic controller

/ / app/http/controller/ definition UserControllernamespace App\ Http\ Controllers;use App\ Http\ Controllers\ Controller;use App\ Models {/ * display the profile of the specified user * * @ param int $id * @ return\ Illuminate\ View\ View * / public function show ($id) {. }}

Use in routing:

Route::get ('user/ {id}', [UserController::class, 'show'])

two。 Single behavior controller

/ / create a single behavior controller php artisan make:controller GetName-- invokablenamespace App\ Http\ Controllers;use App\ Http\ Controllers\ Controller;use App\ Models\ User;class GetName extends Controller {/ * display the profile of the specified user * * @ param int $id * @ return\ Illuminate\ View\ View * / public function _ _ invoke ($id) {. }}

Use in routing:

Route::get ('user/ {id}', GetName::class) 3. Resource controller

/ / create a resource controller php artisan make:controller UserController-- reosurce using command line mode

Tags: Control controller routing command behavior content foundation way more user profile article resource logic processing good practical parameter name form Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia vpn Huawei Shulou Technology OPPO Reno