使用Hashids库对Laravel雄辩的集合上的ID进行哈希处理 [英] Use Hashids library to hash ids on Laravel eloquent collection

查看:66
本文介绍了使用Hashids库对Laravel雄辩的集合上的ID进行哈希处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要从数据库中获取一组任务作为有说服力的集合,然后将集合发送到我的视图中,在其中执行 foreach .没问题除此之外,我需要在视图中引用任务 id (URL操作等).但是我显然不希望在源代码中使用它,因此我正在使用此库来对ID.但是在视图中这样做似乎是错误的.

I'm grabbing a set of tasks from a database as an eloquent collection, then I'm sending the collection to my view where I do a foreach. No problems here. Except, I need to reference the task id in my view (URL action, etc). But I obviously don't want this in the source, so I'm using this library to hash the id. But doing this in the view seems wrong.

有什么方法可以哈希模型或控制器中的ID?

Is there any way to hash the id in the model or controller?

这是我在控制器中调用集合的方式:

Here's how I'm calling the collection in my controller:

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

这是我当前在视图中对ID进行哈希处理的方式:

This is how I'm currently hashing the id in my view:

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

推荐答案

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

You could do it using an accessor method. First, append a new attribute at the top of your Task model:

protected $appends = ['hashid'];

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

Then, in the same model, create an accessor that populates the attribute:

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

拥有这些属性后,只需在视图中调用附加属性即可:

Once you have those, just call the appended attribute in your view:

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

这篇关于使用Hashids库对Laravel雄辩的集合上的ID进行哈希处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆