6

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

2 Answers 2

8

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) }}">
2
  • I went a different route, by modifying getRouteKey() function in my model, then using this as my anchor: <a href="{{ route('tasks.markascompleted', [$task] }}">. The [$task] laravel does the dirty work of fetching the ID for me. But this is a option as well, I'll accept it. Apr 25, 2015 at 22:09
  • public function getRouteKey() { return Hashids::encode($this->getKey()); } Apr 25, 2015 at 22:09
0

You can use the Laravel Hashslug library, which does this for you automatically with minimal setup:

class Task extends Model {
    use HasHashSlug;
}
<a href="{{ action('TaskController@markAsCompleted', $task) }}">

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.