php - 修改 Laravel 模型响应以使用不同的 ID

标签 php laravel laravel-7 hashids

我希望在模型发送回客户端之前进行某种“拦截”并更改模型中的字段。我有一个 API,其端点类似于以下内容:

Route::get('users/{user}', 'Api\UserController@user');

我的应用程序使用 vinkla/laravel-hashids ,因此就客户端应用程序而言,要查询的 ID 应该类似于 K6LJwKJ1M8,而不是 1。目前,我可以查询提供哈希 ID 的用户,但响应返回的是数字/自动递增 ID。

例如对于诸如 /api/users/K6LJwKJ1M8 之类的查询,我收到以下响应:

{
    "id": 1,
    "address": null,
    "telephone": null,
    "name": "TestNameHere",
    "description": null,
    ...
}

Laravel 中有没有一种好方法可以修改响应中返回的所有用户对象以使用 vinkla/laravel-hashids ID,而不是自动递增 ID?

理想情况下,上述响应将变为:

{
    "id": K6LJwKJ1M8,
    "address": null,
    "telephone": null,
    "name": "TestNameHere",
    "description": null,
    ...
}

我认为使用 getRouteKey 之类的方法会起作用,但它不会更改在 JSON 响应中发送的对象。

例如

public function getRouteKey() {
    return Hashids::encode($this->attributes['id']);
}

如果有一个地方可以更改此设置,那就太好了,因为我的应用程序有大约 40 条不同的路由,否则我需要“手动”更改这些路由(例如,在发送响应之前执行类似 $user- 的操作) >id = Hashids::encode($id))

最佳答案

您可以实现CastsAttributes interface :

Classes that implement this interface must define a get and set method. The get method is responsible for transforming a raw value from the database into a cast value, while the set method should transform a cast value into a raw value that can be stored in the database.

在您的 app 目录中创建一个名为 Casts 的目录,并创建一个名为 UserCode 的类:

namespace App\Casts;

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use ...\Hashids;

class UserCode implements CastsAttributes
{
    public function get($model, $key, $value, $attributes)
    {
        return Hashids::encode($value);
    }

    public function set($model, $key, $value, $attributes)
    {
        return Hashids::decode($value);
    }
}

然后在您的用户模型中将 UserCode 转换添加到 id 值:

use App\Casts\UserCode; // <--- make sure to import the class
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $casts = [
        'id' => UserCode::class,
    ];
}

然后,如果您执行User::find(1)->id,您将获得哈希值或访问/user/1,它将返回用户散列 ID。 credit .

请注意,除非您实现了某些功能,否则您无法通过散列 ID 找到用户/user/hashed_id 将给出 404。

关于php - 修改 Laravel 模型响应以使用不同的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63207914/

相关文章:

php - 动态替换所有<img>标签的 "src"属性

php - Laravel API 返回不同模型用户

php - 实现 Searchable,Laravel 的一个搜索特性

javascript - 在 laravel 7 中在哪里添加 Javascript/JQuery?

php - 使用 foreach 进行 api 调用以循环数组

command-line-interface - php cli include_once 错误

PHP 通用表单生成器/生成器

javascript - 如何从 Jquery 中的 PHP 循环获取 Href 文本

php - Laravel 5.6 奇怪的行为 - Laravel 在重命名后看不到 Controller

laravel-7 - 授权后的 Laravel Sanctuary token