Table of Contents
1. HTTP routing
1. Basic routing
2. Routing parameters
2. Create controller
3. Advanced routing
1. Named routing
2. Routing group
Home Backend Development PHP Tutorial Detailed explanation of examples of HTTP routing and creation of controllers and resource routing in Laravel5.2

Detailed explanation of examples of HTTP routing and creation of controllers and resource routing in Laravel5.2

Sep 11, 2017 am 09:54 AM
http controller

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!';
});
Copy after login

For common 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); //响应所有请求
Copy after login

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]+']);
Copy after login

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 routing


//命名闭包路由
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'));
Copy after login

2. Routing group

2.1 Route prefixes and namespaces

For example, there are two routes pointing to controller methods


Route::get('admin/login', 'Admin\IndexController@login');
Route::get('admin/index', 'Admin\IndexController@index');
Copy after login

Take the first For example,

Parameter 1: admin/login means that this URI is requesting the admin/login resource under the website root directory, and the full address is http://domain name/admin/login (Apache's route rewriting is enabled 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\Admin\IndexController The login method in the controller.

Obviously, the URIs and controller methods of the two routes have the same parts. Then, enabling route grouping can extract the common parts:


// 第一个数组参数中,prefix 键定义 URI 的公共部分,namespace 键定义方法名(命名空间语法)的公共部分
Route::group(array('prefix' => 'admin', 'namespace' => 'Admin'), function(){
    Route::get('login', 'IndexController@login');
    Route::get('index', 'IndexController@index');
});
Copy after login

2.2 Resource routing

Resource routing is the route mapped to the resource controller. Laravel resource controller has built-in 7 ways to add, delete, modify and check resources and 7 routes.

First, create Resource Controller ArticleController


php artisan make:controller Admin\ArticleController  --resource
Copy after login

Please ensure that the Admin directory exists in the app/Http/Controllers directory for the above command .

This generates the resource controller file in app/Http/Controllers/Admin/ArticleController.php. 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)
    {
        //
    }
}
Copy after login

Then, define resource routing . Here I still choose to define it under the routing group, just define one


Route::group(array(&#39;prefix&#39; => &#39;admin&#39;, &#39;namespace&#39; => &#39;Admin&#39;), function(){ 
    Route::get(&#39;login&#39;, &#39;IndexController@login&#39;);
    Route::get(&#39;index&#39;, &#39;IndexController@index&#39;);
    // 资源路由
    Route::resource(&#39;article&#39;, &#39;ArticleController&#39;);
});
Copy after login

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 Detailed explanation of examples of HTTP routing and creation of controllers and resource routing in Laravel5.2. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to properly calibrate your Xbox One controller on Windows 11 How to properly calibrate your Xbox One controller on Windows 11 Sep 21, 2023 pm 09:09 PM

Since Windows has become the gaming platform of choice, it's even more important to identify its gaming-oriented features. One of them is the ability to calibrate an Xbox One controller on Windows 11. With built-in manual calibration, you can get rid of drift, random movement, or performance issues and effectively align the X, Y, and Z axes. If the available options don't work, you can always use a third-party Xbox One controller calibration tool. Let’s find out! How do I calibrate my Xbox controller on Windows 11? Before proceeding, make sure you connect your controller to your computer and update your Xbox One controller's drivers. While you're at it, also install any available firmware updates. 1. Use Wind

What does http status code 520 mean? What does http status code 520 mean? Oct 13, 2023 pm 03:11 PM

HTTP status code 520 means that the server encountered an unknown error while processing the request and cannot provide more specific information. Used to indicate that an unknown error occurred when the server was processing the request, which may be caused by server configuration problems, network problems, or other unknown reasons. This is usually caused by server configuration issues, network issues, server overload, or coding errors. If you encounter a status code 520 error, it is best to contact the website administrator or technical support team for more information and assistance.

What is http status code 403? What is http status code 403? Oct 07, 2023 pm 02:04 PM

HTTP status code 403 means that the server rejected the client's request. The solution to http status code 403 is: 1. Check the authentication credentials. If the server requires authentication, ensure that the correct credentials are provided; 2. Check the IP address restrictions. If the server has restricted the IP address, ensure that the client's IP address is restricted. Whitelisted or not blacklisted; 3. Check the file permission settings. If the 403 status code is related to the permission settings of the file or directory, ensure that the client has sufficient permissions to access these files or directories, etc.

Understand common application scenarios of web page redirection and understand the HTTP 301 status code Understand common application scenarios of web page redirection and understand the HTTP 301 status code Feb 18, 2024 pm 08:41 PM

Understand the meaning of HTTP 301 status code: common application scenarios of web page redirection. With the rapid development of the Internet, people's requirements for web page interaction are becoming higher and higher. In the field of web design, web page redirection is a common and important technology, implemented through the HTTP 301 status code. This article will explore the meaning of HTTP 301 status code and common application scenarios in web page redirection. HTTP301 status code refers to permanent redirect (PermanentRedirect). When the server receives the client's

Learning Laravel from scratch: Detailed explanation of controller method invocation Learning Laravel from scratch: Detailed explanation of controller method invocation Mar 10, 2024 pm 05:03 PM

Learning Laravel from scratch: Detailed explanation of controller method invocation In the development of Laravel, controller is a very important concept. The controller serves as a bridge between the model and the view, responsible for processing requests from routes and returning corresponding data to the view for display. Methods in controllers can be called by routes. This article will introduce in detail how to write and call methods in controllers, and will provide specific code examples. First, we need to create a controller. You can use the Artisan command line tool to create

How to use Nginx Proxy Manager to implement automatic jump from HTTP to HTTPS How to use Nginx Proxy Manager to implement automatic jump from HTTP to HTTPS Sep 26, 2023 am 11:19 AM

How to use NginxProxyManager to implement automatic jump from HTTP to HTTPS. With the development of the Internet, more and more websites are beginning to use the HTTPS protocol to encrypt data transmission to improve data security and user privacy protection. Since the HTTPS protocol requires the support of an SSL certificate, certain technical support is required when deploying the HTTPS protocol. Nginx is a powerful and commonly used HTTP server and reverse proxy server, and NginxProxy

HTTP 200 OK: Understand the meaning and purpose of a successful response HTTP 200 OK: Understand the meaning and purpose of a successful response Dec 26, 2023 am 10:25 AM

HTTP Status Code 200: Explore the Meaning and Purpose of Successful Responses HTTP status codes are numeric codes used to indicate the status of a server's response. Among them, status code 200 indicates that the request has been successfully processed by the server. This article will explore the specific meaning and use of HTTP status code 200. First, let us understand the classification of HTTP status codes. Status codes are divided into five categories, namely 1xx, 2xx, 3xx, 4xx and 5xx. Among them, 2xx indicates a successful response. And 200 is the most common status code in 2xx

Send POST request with form data using http.PostForm function Send POST request with form data using http.PostForm function Jul 25, 2023 pm 10:51 PM

Use the http.PostForm function to send a POST request with form data. In the http package of the Go language, you can use the http.PostForm function to send a POST request with form data. The prototype of the http.PostForm function is as follows: funcPostForm(urlstring,dataurl.Values)(resp*http.Response,errerror)where, u

See all articles