Spread the love

Laravel provides inbuilt library to encrypt and decrypt the strings. Laravel usage OpenSSL to provide AES-256 encryption which creates long encrypted string. Encryption and decryption is a technique to hide the useful some information in a form which is not readable.

In this tutorial i will show you to encrypt and decrypt the string using laravel crypt library. I will take simple example of a string and then will encrypt and decrypt in controller.

Below is the syntax

<?php 
encrypt($string);
decrypt($encrypted_string);

//OR

use Illuminate\Support\Facades\Crypt;

Crypt::encryptString($string);
Crypt::decryptString($encrypted_string);

So let’s take an simple example of encrypt and decrypt string in laravel 8

Step 1 : Generate App key

Before using the crypt class make sure you have generated the app key and if not then generate using artisan command as below.

php artisan key:generate


Step 2 : Create a controller

Next step is to create the controller and add the necessary imports and class. You can create by Laravel artisan or manually.

php artisan make:controller PostController

Now, add use Illuminate\Support\Facades\Crypt; and methods

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Crypt;

class PostController extends Controller
{

    
    public function index()
    {
         $encrypted_string = Crypt::encryptString("Readerstacks.com");
         $decrypted_string = Crypt::decryptString($encrypted_string);
        
          //or using helper function

         $encrypted_string = encrypt("Readerstacks.com");
         $decrypted_string = decrypt($encrypted_string);

         dump($encrypted_string);
         dump($decrypted_string);
         return  "DONE";
   }
    
}

Here we used Crypt::encryptString and encrypt to encrypt the string and Crypt::decryptString and decrypt to decrypt the string.

Step 3 : Create Routes

Thirst step is to create the routes to check our implementation

<?php

use Illuminate\Support\Facades\Route;
use \App\Http\Controllers\PostController;

Route::any('/encrypt-decrypt-example',[PostController::class, 'index']); 

Now, if we access the URL /encrypt-decrypt-example, we will get below output.

Screenshot:

Leave a Reply