search
HomeBackend DevelopmentPHP TutorialDetailed explanation of examples of HTTP routing and creation of controllers and resource routing in Laravel5.2

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 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 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'));

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');

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');
});

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

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)
    {
        //
    }
}

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;);
});

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
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
What data can be stored in a PHP session?What data can be stored in a PHP session?May 02, 2025 am 12:17 AM

PHPsessionscanstorestrings,numbers,arrays,andobjects.1.Strings:textdatalikeusernames.2.Numbers:integersorfloatsforcounters.3.Arrays:listslikeshoppingcarts.4.Objects:complexstructuresthatareserialized.

How do you start a PHP session?How do you start a PHP session?May 02, 2025 am 12:16 AM

TostartaPHPsession,usesession_start()atthescript'sbeginning.1)Placeitbeforeanyoutputtosetthesessioncookie.2)Usesessionsforuserdatalikeloginstatusorshoppingcarts.3)RegeneratesessionIDstopreventfixationattacks.4)Considerusingadatabaseforsessionstoragei

What is session regeneration, and how does it improve security?What is session regeneration, and how does it improve security?May 02, 2025 am 12:15 AM

Session regeneration refers to generating a new session ID and invalidating the old ID when the user performs sensitive operations in case of session fixed attacks. The implementation steps include: 1. Detect sensitive operations, 2. Generate new session ID, 3. Destroy old session ID, 4. Update user-side session information.

What are some performance considerations when using PHP sessions?What are some performance considerations when using PHP sessions?May 02, 2025 am 12:11 AM

PHP sessions have a significant impact on application performance. Optimization methods include: 1. Use a database to store session data to improve response speed; 2. Reduce the use of session data and only store necessary information; 3. Use a non-blocking session processor to improve concurrency capabilities; 4. Adjust the session expiration time to balance user experience and server burden; 5. Use persistent sessions to reduce the number of data read and write times.

How do PHP sessions differ from cookies?How do PHP sessions differ from cookies?May 02, 2025 am 12:03 AM

PHPsessionsareserver-side,whilecookiesareclient-side.1)Sessionsstoredataontheserver,aremoresecure,andhandlelargerdata.2)Cookiesstoredataontheclient,arelesssecure,andlimitedinsize.Usesessionsforsensitivedataandcookiesfornon-sensitive,client-sidedata.

How does PHP identify a user's session?How does PHP identify a user's session?May 01, 2025 am 12:23 AM

PHPidentifiesauser'ssessionusingsessioncookiesandsessionIDs.1)Whensession_start()iscalled,PHPgeneratesauniquesessionIDstoredinacookienamedPHPSESSIDontheuser'sbrowser.2)ThisIDallowsPHPtoretrievesessiondatafromtheserver.

What are some best practices for securing PHP sessions?What are some best practices for securing PHP sessions?May 01, 2025 am 12:22 AM

The security of PHP sessions can be achieved through the following measures: 1. Use session_regenerate_id() to regenerate the session ID when the user logs in or is an important operation. 2. Encrypt the transmission session ID through the HTTPS protocol. 3. Use session_save_path() to specify the secure directory to store session data and set permissions correctly.

Where are PHP session files stored by default?Where are PHP session files stored by default?May 01, 2025 am 12:15 AM

PHPsessionfilesarestoredinthedirectoryspecifiedbysession.save_path,typically/tmponUnix-likesystemsorC:\Windows\TemponWindows.Tocustomizethis:1)Usesession_save_path()tosetacustomdirectory,ensuringit'swritable;2)Verifythecustomdirectoryexistsandiswrita

See all articles

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools