温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在php中利用Laravel定义路由

发布时间:2021-04-23 16:18:53 来源:亿速云 阅读:133 作者:Leah 栏目:编程语言

本篇文章为大家展示了怎么在php中利用Laravel定义路由,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

php有什么特点

1、执行速度快。2、具有很好的开放性和可扩展性。3、PHP支持多种主流与非主流的数据库。4、面向对象编程:PHP提供了类和对象。5、版本更新速度快。6、具有丰富的功能。7、可伸缩性。8、功能全面,包括图形处理、编码与解码、压缩文件处理、xml解析等。

1.get方式

Route::get('/', function () {
    return view('welcome');
});

好处是把回调的实现和使用场所隔离,这段代码是意思是,当get方式访问根目录时返回welcome视图。

2.info方法

Route::get('admin/info','Admin\IndexController@info');

访问http://your-app.dev/admin/info时,调用命名空间Admin下的IndexController控制器里的info方法。这样写是不是麻烦,所以有了路由组,统一指定中间件,前缀和命名空间。

3.使用路由

//在浏览器直接访问,跳转到welcome视图,视图路径在public/resources/views/
Route::get('/', function () {
    return view('welcome');
});
 
//在浏览器直接访问,返回hello world
Route::get("route1", function () {
    return "hello world";
});
 
//因为是post请求,不可以在浏览器地址栏直接访问
Route::post("route2", function () {
    return "hello world";
});
 
//match: 可以定义接收get或post请求
Route::match(['get','post'], "reute3", function () {
    return "hello world";
});
 
//any: 可以接收get和post请求
Route::any("route4", function () {
    return "hello world";
});
 
//路由接收参数,php中的字符串拼接用 "."
Route::get("user1/{id}", function($id){
    return "id-->" . $id;
});
 
//在user2/{id?} 后面加个问号代表参数不是必要的,可以在function中给个默认值
Route::get("user2/{id?}", function($id = 5){
    return "id-->" . $id;
});
 
//参数校验,在最后面加上正折表达,这里代表username只能是字母
Route::get("user3/{username}", function($username) {
    return "username-->" . $username;
})->where("username","[A-Za-z]+");
 
//路由别名,只要在后面加个数组,注意数组第一个元素是"as" => "center" ,第二个元素是function
Route::get("user4/mamber-center", ["as" => "center" , function(){
    //使用routes可以返回对应的路径
    return route("center");
}]);
 
//路由群组,加前缀,member.可以通过member/user1访问到第一个,
//通过member/user2访问到第二个
Route::group(["prefix" => "member"], function(){
 
    Route::get("user1",function(){
        return "hello world";
    });
 
    Route::get("user2",["as" => "group_route", function(){
        return route("group_route");
    }]);
 
});

上述内容就是怎么在php中利用Laravel定义路由,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI