Encrypt survey ID

User
$surveys = Survey::orderBy('id', 'desc')->paginate(config('app.records_per_page'));
change id integer to encrypted using crypt
Assistant
To **encrypt the `id` field in your paginated `$surveys` collection**, you can’t modify the SQL query itself to return encrypted IDs, since Laravel’s `Crypt::encrypt()` is a PHP function, not SQL.

Instead, you can **map** over the collection *after* retrieving the paginated data and encrypt each `id` like this:

use IlluminateSupportFacadesCrypt;

$surveys = Survey::orderBy('id', 'desc')->paginate(config('app.records_per_page'));

// Encrypt the IDs for each survey item
$surveys->getCollection()->transform(function ($survey) {
    $survey->encrypted_id = Crypt::encrypt($survey->id);
    unset($survey->id); // optionally remove the plain ID
    return $survey;
});

### Now in your Blade/view:
Use `{{ $survey->encrypted_id }}` instead of `{{ $survey->id }}`.

### To Decrypt:
If you receive the encrypted ID in a controller route, decrypt it like so:

$decryptedId = Crypt::decrypt($request->encrypted_id);

Let me know if you're using `route()` and want to pass encrypted IDs in URLs too.

Leave a Comment

Your email address will not be published. Required fields are marked *