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

标签 php laravel laravel-5 hashids

我从数据库中抓取一组任务作为一个 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/

相关文章:

php - Laravel - 从一个表中获取另一个表中不存在的记录并附加 where 子句

php - laravel - 找不到新服务提供商的类

php - 使用 PHP 从 MySQL 动态选择多个下拉选项

php - 来自mysql中多个表的不同值

php - 如何在触发下载之前在laravel中设置标题

laravel - 如何在 Laravel Vue 中沿着 side bootstrap 使用 zurb Foundation?

php - Laravel if then 条件

php - 查询未执行

php - 编写此查询的更好方法,以便将其转换为 laravel eloquent

php - 在没有 $request 的情况下执行 Laravel 验证