设为首页 加入收藏

TOP

Laravel 5.2 二、HTTP路由、创建控制器 与 资源路由(一)
2019-08-24 00:02:22 】 浏览:75
Tags:Laravel 5.2 HTTP 路由 创建 控制器 资源

一、HTTP路由

所有路由都定义在 App\Providers\RouteServiceProvider 类载入的 app/Http/routes.php文件中。

 

1. 基本路由

简单的 Laravel 路由只接受一个 URI 和一个闭包

1
2
3
Route::get( 'foo' function  () {
     return  'Hello, Laravel!' ;
});

 

对于常见的 HTTP 请求,Laravel 有以下几种路由

1
2
3
4
5
6
7
8
9
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 );  //响应所有请求

其中,$callback 可以是一个闭包,也可以是一个控制器方法。实际上,在开发中有不少情况是用作控制器方法的。

  

2. 路由参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//单个路由参数
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]+' ]);

  

二、创建控制器

使用 Artisan 命令创建 php artisan make:controller UserController 

现在,在 app/Http/Controllers 这个控制器目录下就生成了 UserController.php 的控制器文件。

 

三、高级路由

1. 命名路由

1
2
3
4
5
6
7
8
9
//命名闭包路由
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. 路由分组

2.1 路由前缀和命名空间

例如,有两条指向控制器方法的路由

1
2
Route::get( 'admin/login' 'Admin\IndexController@login' );
Route::get( 'admin/index' 'Admin\IndexController@index' );

 

拿第一条来说,

参数一:admin/login  表示这个 URI 在请求网站根目录下的 admin/login 资源,完

首页 上一页 1 2 3 下一页 尾页 1/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Thinkphp5 对接百度云对象存储 BO.. 下一篇Php7.3 could not find driver

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目