


Introduction to HTTP routing, creating controllers and resource routing in Laravel5.2 (with code)
This article brings you an introduction to HTTP routing, creation of controllers and resource routing in Laravel 5.2 (with code). It has certain reference value. Friends in need can refer to it. I hope it will help You helped.
1. HTTP routing
All routes are defined in the app/Http/routes.php file loaded by the App\Providers\RouteServiceProvider class.
1. Basic routing
Simple Laravel routing only accepts a URI and a closure
Route::get('foo', function () { return 'Hello, Laravel!'; });
For common For HTTP requests, Laravel has the following routes
Route::get($uri, $callback); //响应 get 请求 Route::post($uri, $callback); Route::put($uri, $callback); Route::patch($uri, $callback); Route::delete($uri, $callback); Route::options($uri, $callback); Route::match(['get', 'post'], $uri, $callback); //响应 get, post 请求 Route::any('foo', $callback); //响应所有请求
Among them, $callback can be a closure or a controller method. In fact, there are many situations in development where controller methods are used.
2. Routing parameters
//单个路由参数 Route::get('user/{id}', function ($id) { return 'User '.$id; }); //多个路由参数 Route::get('posts/{post}/comments/{comment}', function ($postId, $commentId) { // }); //单个路由参数(可选) Route::get('user/{id?}', function ($id = 1) { return 'User '.$id; }); //多个路由参数(可选) Route::get('posts/{post}/comments/{comment?}', function ($postId, $commentId = 1) { // }); //注意:多个参数时,只可以对最后一个参数设置可选,其他位置设置可选会解析错误 // 正则约束单个参数 Route::get('user/{name?}', function ($name = 'Jone') { return $name; })->where('name', '\w+'); //约束参数为单词字符(数字、字母、下划线) // 正则约束多个参数 Route::get('user/{id}/{name}', function ($id, $name) { // })->where(['id' => '[0-9]+', 'name' => '[a-z]+']);
2. Create controller
Use Artisan command to create php artisan make:controller UserController
Now, the controller file UserController.php is generated in the controller directory app/Http/Controllers.
3. Advanced routing
1. Named route
//命名闭包路由 Route:get('user', array('as' => 'alial', function(){}); //或 name 方法链 Route:get('user', function(){})->name('alias'); //命名控制器方法路由 Route:get('user', array('uses' => 'Admin\IndexController@index', 'as' => 'alias')); //或 name 方法链 Route:get('user', 'Admin\IndexController@index')->name('alias'));
2. Routing group
2.1 Routing prefix sum Namespace
For example, there are two routes pointing to the controller method
Route::get('admin/login', 'Admin\IndexController@login'); Route::get('admin/index', 'Admin\IndexController@index');
Take the first one,
Parameter one:admin /login means that this URI is requesting the admin/login resource in the root directory of the website. The complete address is http://domain name/admin/login (Apache's route rewriting is turned on here, hiding "index.php") , this request is mapped to the controller method specified in the second parameter. Note that the website root directory is the directory where the entry file is located, which is the public directory in Laravel. It is best to point here when configuring the server.
Parameter two: Admin\IndexController@login means that this controller method is in the App\Http\Controllers namespace, and the connection is App\Http\Controllers\ The login method in the Admin\IndexController controller.
Obviously, the URI and controller method of the two routes have the same parts. Then, enabling route grouping can extract the common part:
// 第一个数组参数中,prefix 键定义 URI 的公共部分,namespace 键定义方法名(命名空间语法)的公共部分 Route::group(array('prefix' => 'admin', 'namespace' => 'Admin'), function(){ Route::get('login', 'IndexController@login'); Route::get('index', 'IndexController@index'); });
2.2 Resource routing
Resource routing is the route mapped to the resource controller. Laravel resource controller has built-in 7 methods for adding, deleting, modifying and checking resources and 7 routes.
First, create the resource controller ArticleController
php artisan make:controller Admin/ArticleController --resource
This will generate the resource controller in the app/Http/Controllers/Admin/ArticleController.php file (Admin folder It will be created automatically if it does not exist). The 7 built-in methods are as follows:
<?php namespace App\Http\Controllers\Admin; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class LinksController extends Controller { /** * 显示一个资源的列表 * * @return \Illuminate\Http\Response */ public function index() { // } /** * 显示一个表单来创建一个新的资源 * * @return \Illuminate\Http\Response */ public function create() { // } /** * 保存最新创建的资源 * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // } /** * 显示指定的资源 * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * 显示一个表单来编辑指定的资源 * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * 更新指定的资源 * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * 删除指定的资源 * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } }
Then, define resource routing. Here I still choose to define it under the routing group, just define one
Route::group(array('prefix' => 'admin', 'namespace' => 'Admin'), function(){ Route::get('login', 'IndexController@login'); Route::get('index', 'IndexController@index'); // 资源路由 Route::resource('article', 'ArticleController'); });
Finally, check the route. With resource controller and resource routing, you can look at the HTTP request methods for the above 7 methods.
Use the Artisan command php artisan route:list to list all current routes, including request methods, URIs, controller methods, and middleware.
The above is the detailed content of Introduction to HTTP routing, creating controllers and resource routing in Laravel5.2 (with code). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Both Django and Laravel are full-stack frameworks. Django is suitable for Python developers and complex business logic, while Laravel is suitable for PHP developers and elegant syntax. 1.Django is based on Python and follows the "battery-complete" philosophy, suitable for rapid development and high concurrency. 2.Laravel is based on PHP, emphasizing the developer experience, and is suitable for small to medium-sized projects.

How does Laravel play a role in backend logic? It simplifies and enhances backend development through routing systems, EloquentORM, authentication and authorization, event and listeners, and performance optimization. 1. The routing system allows the definition of URL structure and request processing logic. 2.EloquentORM simplifies database interaction. 3. The authentication and authorization system is convenient for user management. 4. The event and listener implement loosely coupled code structure. 5. Performance optimization improves application efficiency through caching and queueing.

PHP and Laravel are not directly comparable, because Laravel is a PHP-based framework. 1.PHP is suitable for small projects or rapid prototyping because it is simple and direct. 2. Laravel is suitable for large projects or efficient development because it provides rich functions and tools, but has a steep learning curve and may not be as good as pure PHP.

LaravelisabackendframeworkbuiltonPHP,designedforwebapplicationdevelopment.Itfocusesonserver-sidelogic,databasemanagement,andapplicationstructure,andcanbeintegratedwithfrontendtechnologieslikeVue.jsorReactforfull-stackdevelopment.

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

Want to learn the Laravel framework, but suffer from no resources or economic pressure? This article provides you with free learning of Laravel, teaching you how to use resources such as online platforms, documents and community forums to lay a solid foundation for your PHP development journey from getting started to master.

The Laravel development project was chosen because of its flexibility and power to suit the needs of different sizes and complexities. Laravel provides routing system, EloquentORM, Artisan command line and other functions, supporting the development of from simple blogs to complex enterprise-level systems.

Laravel provides a comprehensive Auth framework for implementing user login functions, including: Defining user models (Eloquent model), creating login forms (Blade template engine), writing login controllers (inheriting Auth\LoginController), verifying login requests (Auth::attempt) Redirecting after login is successful (redirect) considering security factors: hash passwords, anti-CSRF protection, rate limiting and security headers. In addition, the Auth framework also provides functions such as resetting passwords, registering and verifying emails. For details, please refer to the Laravel documentation: https://laravel.com/doc
