How to pass encrypted ID as route parameter in Laravel Route Model Binding

652 Views Asked by At

I want to pass encrypted ID as route parameter. Currently, I'm using Route model binding and it returns a 404

1

There are 1 best solutions below

1
Kamlesh Paul On

You can create a custom resolver for that modal like

use Illuminate\Support\Facades\Crypt;

/**
 * Retrieve the model for a bound value.
 *
 * @param  mixed  $value
 * @param  string|null  $field
 * @return \Illuminate\Database\Eloquent\Model|null
 */
public function resolveRouteBinding($encryptedId, $field = null)
{
    return $this->where('id', Crypt::decryptString ($encryptedId))->firstOrFail();
}

in the above code you can get the encrypted data as $encryptedId you can decrypt and used in query to perform search


same thing you can do in RouteServiceProvider

use App\Models\User;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Crypt;

 
/**
 * Define your route model bindings, pattern filters, etc.
 *
 * @return void
 */
public function boot()
{
    Route::bind('user', function ($encryptedId) {
        return User::where('id', Crypt::decryptString ($encryptedId))->firstOrFail();
    });
 
    // ...
}

ref link https://laravel.com/docs/9.x/routing#customizing-the-resolution-logic