本文实例讲述了laravel框架创建路由的方法。分享给大家供大家参考,具体如下:
我这里使用的laravel版本是5.6,路由位置在routes/web.php中,所以我们在这个文件中添加我们想要添加的路由。
1.基础路由
?
1
2
3
4
5
6
7
8
|
//get请求,结果如下图
route::get( 'basic1' , function (){
return 'hello world' ;
});
//post请求,这里不展示结果图
route::post( 'basic2' , function (){
return 'post' ;
});
|
2.多请求路由
?
1
2
3
4
5
6
7
8
|
//自定义多请求,自定义的请求放在下面的数组中
route::match([ 'get' , 'post' ], 'multy' , function (){
return "多请求路由" ;
});
//响应所有请求
route::any( 'multy2' , function (){
return '响应所有请求' ;
});
|
自定义多请求
响应所有请求
3.路由参数
?
1
2
3
4
|
//必选参数
route::get( 'user/{id}' , function ( $id ){
return '用户的id是' . $id ;
});
|
?
1
2
3
4
|
//可选参数,无参数默认值为doubly
route::get( 'name/{name?}' , function ( $name = 'doubly' ){
return '用户名为' . $name ;
});
|
?
1
2
3
4
|
//字段验证,名字必须为字母
route::get( 'name/{name?}' , function ( $name = 'doubly' ){
return '用户名为' . $name ;
})->where( 'name' , '[a-za-z]+' );
|
?
1
2
3
4
|
//多个参数,并且带有参数验证
route::get( 'user/{id}/{name?}' , function ( $id , $name = 'doubly' ){
return "id为{$id}的用户名为{$name}" ;
})->where([ 'id' => '\\d+' , 'name' => '[a-za-z]+' ]);
|
4.路由别名
?
1
2
3
4
|
//路由别名
route::get( 'user/center' ,[ 'as' => 'center' , function (){
return '路由别名:' .route( 'center' );
}]);
|
使用别名的好处是什么呢?
当我们需要修改路由的时候,比如将user/center
改成user/member-center
的时候,我们代码中使用route('cneter')
生成的url是不需要修改的。
6.路由群组
?
1
2
3
4
5
6
7
8
9
10
|
//路由群组
route::group([ 'prefix' => 'member' ], function (){
route::get( 'basic1' , function (){
return '路由群组中的basic1' ;
});
route::get( 'basic2' , function (){
return '路由群组中的basic2' ;
});
});
|
通过laravel.test/member/basic2访问
7.路由中输出视图
?
1
2
3
4
|
//路由中输出视图
route::get( 'view' , function (){
return view( 'welcome' );
});
|
welcome.blade.php模板内容
?
1
|
<h1>这是路由中输出的视图</h1>
|
希望本文所述对大家基于Laravel框架的PHP程序设计有所帮助。
原文链接:https://blog.csdn.net/qq_18335837/article/details/81283553
相关文章
猜你喜欢
- ASP.NET本地开发时常见的配置错误及解决方法? 2025-06-10
- ASP.NET自助建站系统的数据库备份与恢复操作指南 2025-06-10
- 个人网站服务器域名解析设置指南:从购买到绑定全流程 2025-06-10
- 个人网站搭建:如何挑选具有弹性扩展能力的服务器? 2025-06-10
- 个人服务器网站搭建:如何选择适合自己的建站程序或框架? 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-25 14
-
2025-05-27 10
-
2025-05-29 37
-
2025-05-25 88
-
2025-05-27 78
热门评论