How to encrypt or decript id in laravel?
if your URL structure for viewing the information was something like this type https://itechxpert.in/user/2.
if any one changed the id[last numeric number in url] was able to view the information of other users. This was a huge security issue.
URL show should be in this form https://itechxpert.in/user/sdfsdkfksjflksfsigjkkjhhajj
To avoid such issues we will encrypt id in url of laravel application.
Method One :- Laravel Encrypter/Decrypter inbuilt function.
Laravel provide bydefault feature for encryption/ decryption. You can encrypt a value using the encrypt helper function and decrypt the encrypted value using a decrypt
helper function. Encryption of data is done by calling the encrypt ($value) function. and decryption of data is done by calling the decrypt ($enctypedvalue) function.
File name : index.php
$id = 2;
$user_id = $id;
$encrypted_value = encrypt($user_id);
<a href="{{url('goid/'.$encrypted_value)}}">Click here</a>
How to decrypt encripted value in laravel?
File name : index.php
public function test_cost(Request $request,$id)
{
//$user_id = $id;
$user_id = decrypt($id);
$userlist= Testdetail::get();
return view('admin.userinfo',compact('userlist','user_id'));
}
Note :-
File name : index.php
Before applying Laravel Encryption on your Laravel project, you must include keys under the config/app.php configuration file. Use the following command to generate this key:
php artisan key:generate command
File name : index.php
<?php
$get_id = $users->id;
$get_id = encrypt($get_id);
?>
<a href="{{route('user.show', $get_id)}}">View User</a>
File name : index.php
$decrypted = decrypt($encryptedValue);
Method Two :- Using Laravel's Encryption Package
Install hashid package
File name : index.php
$ composer require hashids/hashids
File name : index.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Hashids\Hashids;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$users = User::all();
$hashids = new Hashids();
return view('users', compact('users','hashids'));
}
}
In the above controller, we imported the Hashids and created its object inside index() function. Then the object is passed to the users view.
File name : users.blade.php :
<?php
$get_id = $users->id;
$get_id = $hashids->encode($get_id);
?>
<a href="{{route('user.show', $get_id)}}">View User</a>
Decode function
The decode function will decode the passed id in the URL.
File name : index.php
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use Hashids\Hashids;
class UserController extends Controller
{
/**
* Show details for the user.
*
* @param Request $request
* @param int $id * @return view
*/
public function show($id)
{
$hashids = new Hashids();
$id = $hashids->decode($id)[0];
$users = User::findOrFail($id);
return view('user/user_details', compact('users'));
}
}
Previous
Next