I'm using the Laravel library for Hashids, which I have it working as it should. However, the way I'm going about it is probably wrong.
Right now, I'd decoding the hashid as below. But I'm finding I'm repeating this step across multiple functions throughout controllers. This can't be the most efficient way:
public function edit($id)
{
$id = Hashids::decode($id)[0];
$task = Auth::user()->tasks()->findOrFail($id);
...
}
Now, I've heard and seen people using Route::bind() in similar situations. But I can't get it to work properly (i.e. decode hashid before id is passing t controller method).
Here's what I'm trying (in my routes.php file)...anything stand out that's wrong? Here's a portion of my code - with it's structure, etc. In short, I want the bind function to work for ALL routes that have an {id}:
Route::group(['middleware' => 'auth'], function()
{
Route::get('tasks', ['as' => 'tasks.index', 'uses' => 'TaskController@index']);
Route::get('tasks/create', ['as' => 'tasks.create', 'uses' => 'TaskController@create']);
Route::post('tasks/store', ['as' => 'tasks.store', 'uses' => 'TaskController@store']);
Route::get('tasks/{id}', ['as' => 'tasks.show', 'uses' => 'TaskController@show']);
Route::get('tasks/{id}/edit', ['as' => 'tasks.edit', 'uses' => 'TaskController@edit']);
Route::patch('tasks/{id}', ['as' => 'tasks.update', 'uses' => 'TaskController@update']);
Route::delete('tasks/{id}/delete', ['as' => 'tasks.destroy', 'uses' => 'TaskController@destroy']);
Route::bind('tasks/{id}', function($id, $route)
{
return \Hashids::decode($id)[0];
});
});
BONUS QUESTION: I'm encoding my id's in the view themselves. Is there a better way? This also seems wrong.
In controller, I'm grabbing the tasks like so:
$tasks = Auth::user()->tasks()->orderBy('created_at', 'desc')->get();
And then I'm hashing the id in my view itself, for example like so. Would be good to have this already hashed when I grab the collection, etc.
<a href="{{ route('tasks.markascompleted', Hashids::encode($task->id)) }}">