How can I encrypt all ids in URL (laravel 9) using repository pattern

Viewed 46

I need to do all url ids encrypted like :

user/edit/1
items/edit/35
posts/details/52

to below url path

user/edit/gd43dfrg
items/edit/sdfg4343
posts/details/fasdf23423

there is lots of areas in repository pattern like UserRepository , UserController blade files and in controllers that id used url ('items/edit/2')

however also in controller some function are passed by objects like

public function itemedit(Items $items)

I tried

$encrypt_val = Crypt::encrypt($value) and $decrypt_val = Crypt::decrypt($encrypt_val );

but I need to do it all over app. There is any short way or Middleware function to do it using repository pattern ?

1 Answers

The proper way to do this would be like so:

Use any boot function of a service provider (e.g. RouteServiceProvider) to define how a route parameter should be invoked:

public function boot()
{
    // Bind any `{order}` route parameter such that it decodes the value before retrieving the order.
    Route::bind('order', function ($value) {
        return User::query()->where('id',  $this->yourDecodeFunction($value))->firstOrFail();
    });
}

Now when you create urls like route('orders.show', yourEncodeFunction($order->id)) from a route

Route::get('/orders/{order}', /*...*/);

your controller method will receive the expected order in its signature i.e.

public function show(Request $request, Order $order) {
    //
}

To improve this code, you can define the getRouteKey() function (part of the UrlRoutable trait) on your Eloquent model to simplify the creation of your routes so that you can call route('orders.show', $order):

// App/Models/Order.php
public function getRouteKey()
{
    return yourEncodeFunction($this->getKey());
}

This will make sure that the route parameter is automatically identified when you pass the complete object to the route call (if you don't override this function yourself it uses the model's primary key).

https://packagist.org/packages/hashids/hashids might be a good package for you if you just want to obfuscate some of the url (note that this package is an 'encoder' and not an 'encrypter').

Related