gpt4 book ai didi

php - 使用 Hashids 库对 Laravel Eloquent 集合中的 ID 进行哈希处理

转载 作者:可可西里 更新时间:2023-11-01 00:31:15 24 4
gpt4 key购买 nike

我从数据库中抓取一组任务作为一个 Eloquent 集合,然后我将集合发送到我执行 foreach 的 View 。这里没有问题。除了,我需要在我的 View 中引用任务 id(URL 操作等)。但我显然不想在源代码中使用这个,所以我使用了 this library对 id 进行哈希处理。但是在 View 中这样做似乎是错误的。

有什么方法可以在模型或 Controller 中散列 id 吗?

下面是我在 Controller 中调用集合的方式:

$tasks = Auth::user()->tasks()->orderBy('created_at', 'desc')->get();

这就是我目前在我的 View 中散列 id 的方式:

<a href="{{ route('tasks.markascompleted', Hashids::encode($task->id)) }}">

最佳答案

您可以使用访问器方法来完成。首先,在 Task 模型的顶部附加一个新属性:

protected $appends = ['hashid'];

然后,在同一个模型中,创建一个填充属性的访问器:

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

一旦你有了这些,只需在你的 View 中调用附加属性:

<a href="{{ route('tasks.markascompleted', $task->hashid) }}">

关于php - 使用 Hashids 库对 Laravel Eloquent 集合中的 ID 进行哈希处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29860371/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com