phplaravellaravel-5hashids

Use Hashids library to hash ids on Laravel eloquent collection


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.

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();

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

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

Solution

  • 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) }}">