How To Encrypt And Decrypt String In Laravel 9

In this article, we will see how to encrypt and decrypt strings in laravel 9. As we all know laravel framework provides more security to the user and that's why laravel provide encrypt of password or string to the user, here we will see encrypt or decrypt a string in laravel 9. Laravel's encryption services provide a simple, convenient interface for encrypting and decrypting text via OpenSSL using AES-256 and AES-128 encryption. 

So, let's see encrypt decrypt a string in laravel 9, laravel 9 in encrypt a string, laravel 9 in decrypt string.

You need to use the Crypt class to start encryptString and decryptString or some data.

use Illuminate\Support\Facades\Crypt;

Example 1:

<?php
 
namespace App\Http\Controllers;
 
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
 
class UsersController extends Controller
{
  public function encrypt()
   {
        $encrypted = Crypt::encryptString('techsolutionstuff');
        print_r($encrypted);
   }
   
    public function decrypt()
    {
         $decrypt= Crypt::decryptString('your_encrypted_string');
         print_r($decrypt);
    }
}

 

 

Example 2:

<?php
 
namespace App\Http\Controllers;
 
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
 
class UsersController extends Controller
{
	$data = Request::all();

	$user = new User();
	$user->password = Crypt::encrypt($data['password']);
	$user->save();
	
	try {
    	$decrypted = Crypt::decrypt($row->password);;
	} catch (DecryptException $e) {
		$e->getMessage();
		info("Error....!!");
	}
}

 


 You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS