前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >最为常用的Laravel操作(2)-路由

最为常用的Laravel操作(2)-路由

原创
作者头像
仁扬
发布2023-07-01 20:27:35
1650
发布2023-07-01 20:27:35
举报
文章被收录于专栏:仁扬笔记仁扬笔记

基本路由

代码语言:php
复制
// 接收一个 URI 和一个闭包
Route::get('hello', function () {
    return 'Hello, Laravel';
});

// 支持的路由方法
Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);

// 支持多个路由方法
Route::match(['get', 'post'], '/', function () {
    //
});

// 注册所有路由方法
Route::any('foo', function () {
    //
});

路由参数

  • 使用花括号包裹
  • 路由参数不能包含 - 字符, 需要的话可以使用 _ 替代
代码语言:php
复制
// 捕获用户 ID
Route::get('user/{id}', function ($id) {
    return 'User '.$id;
});

// 捕获多个参数
Route::get('posts/{post}/comments/{comment}', function ($postId, $commentId) {
    //
});

// 可选参数
Route::get('user/{name?}', function ($name = null) {
    return $name;
});
Route::get('user/{name?}', function ($name = 'John') {
    return $name;
});

// 正则约束
Route::get('user/{name}', function ($name) {
    //
})->where('name', '[A-Za-z]+');

Route::get('user/{id}', function ($id) {
    //
})->where('id', '[0-9]+');

Route::get('user/{id}/{name}', function ($id, $name) {
    //
})->where(['id' => '[0-9]+', 'name' => '[a-z]+']);

命名路由

代码语言:php
复制
// 为路由闭包指定名称
Route::get('user/profile', function () {
    //
})->name('profile');

// 为控制器操作指定名称
Route::get('user/profile', 'UserController@showProfile')->name('profile');

// 使用命名路由生成 URL: 不带参数
$url = route('profile');
return redirect()->route('profile');

// 使用命名路由生成 URL: 附带参数
Route::get('user/{id}/profile', function ($id) {
    //
})->name('profile');
$url = route('profile', ['id' => 1]);

路由群组

中间件
代码语言:php
复制
Route::group(['middleware' => 'auth'], function () {
    Route::get('/', function () {
        // 使用 Auth 中间件
    });
    Route::get('user/profile', function () {
        // 使用 Auth 中间件
    });
});
命名空间
代码语言:php
复制
Route::group(['namespace' => 'Admin'], function(){
    // 控制器在 "App\Http\Controllers\Admin" 命名空间下
});
子域名路由
代码语言:php
复制
Route::group(['domain' => '{account}.myapp.com'], function () {
    Route::get('user/{id}', function ($account, $id) {
        //
    });
});
路由前缀
代码语言:php
复制
Route::group(['prefix' => 'admin'], function () {
    Route::get('users', function () {
        // 匹配 "/admin/users" URL
    });
});

表单方法伪造

代码语言:html
复制
<form action="/foo/bar" method="POST">
    <input type="hidden" name="_method" value="PUT">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>

或使用辅助函数 method_field :

代码语言:txt
复制
{{ method_field('PUT') }}

访问当前路由

代码语言:php
复制
$route  = Route::current();
$name   = Route::currentRouteName();
$action = Route::currentRouteAction();

路由缓存

代码语言:shell
复制
# 添加路由缓存
php artisan route:cache
# 移除路由缓存
php artisan route:clear

路由模型绑定

隐式绑定
代码语言:php
复制
// {user} 与 $user 绑定, 如果数据库中找不到对应的模型实例, 会自动生成 HTTP 404 响应
Route::get('api/users/{user}', function (App\User $user) {
    return $user->email;
});

// 自定义键名: 重写模型 getRouteKeyName 方法
/**
 * Get the route key for the model.
 *
 * @return string
 */
public function getRouteKeyName()
{
    return 'slug';
}
显式绑定

要注册显式绑定, 需要使用路由的 model 方法来为给定参数指定绑定类. 应该在 RouteServiceProvider 类的 boot 方法中定义模型绑定:

代码语言:php
复制
public function boot()
{
    parent::boot();
    Route::model('user', App\User::class);
}

定义一个包含 {user} 参数的路由:

代码语言:php
复制
$router->get('profile/{user}', function(App\User $user) {
    //
});

如果请求 URLprofile/1, 就会注入一个用户 ID1User 实例, 如果匹配的模型实例在数据库不存在, 会自动生成并返回 HTTP 404 响应.

自定义解析逻辑

如果你想要使用自定义的解析逻辑, 需要使用 Route::bind 方法, 传递到 bind 方法的闭包会获取到 URI 请求参数中的值, 并且返回你想要在该路由中注入的类实例:

代码语言:php
复制
public function boot()
{
    parent::boot();
    Route::bind('user', function($value) {
        return App\User::where('name', $value)->first();
    });
}

文章来源于本人博客,发布于 2018-06-02,原文链接:https://imlht.com/archives/155/

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 基本路由
  • 路由参数
  • 命名路由
  • 路由群组
    • 中间件
      • 命名空间
        • 子域名路由
          • 路由前缀
          • 表单方法伪造
          • 访问当前路由
          • 路由缓存
          • 路由模型绑定
            • 隐式绑定
              • 显式绑定
                • 自定义解析逻辑
                相关产品与服务
                消息队列 TDMQ
                消息队列 TDMQ (Tencent Distributed Message Queue)是腾讯基于 Apache Pulsar 自研的一个云原生消息中间件系列,其中包含兼容Pulsar、RabbitMQ、RocketMQ 等协议的消息队列子产品,得益于其底层计算与存储分离的架构,TDMQ 具备良好的弹性伸缩以及故障恢复能力。
                领券
                问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
                http://www.vxiaotou.com