Laravel framework provides hash drivers that allow to hash passwords. There can be a case when hash driver is not implemented for the required hashing algorithm.
This tutorial provides example how to create custom password hasher in Laravel 9 application.
Create a new class that extends AbstractHasher
and implements Hasher
. Define the make
, check
and needsRehash
methods.
<?php
namespace App\Hashing;
use Illuminate\Contracts\Hashing\Hasher;
use Illuminate\Hashing\AbstractHasher;
class Md5Hasher extends AbstractHasher implements Hasher
{
public function make($value, array $options = []): string
{
return md5($value);
}
public function check($value, $hashedValue, array $options = []): bool
{
return $this->make($value) === $hashedValue;
}
public function needsRehash($hashedValue, array $options = []): bool
{
return false;
}
}
Register new hash driver in the boot
method of AppServiceProvider
class.
<?php
namespace App\Providers;
use App\Hashing\Md5Hasher;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
// ...
public function boot(): void
{
// ...
Hash::extend('md5', static function () {
return new Md5Hasher();
});
}
}
In the hashing.php
configuration file, define the default hash driver.
<?php
return [
// ...
'driver' => 'md5',
// ...
];
For testing purpose, we can use the following controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Hash;
class TestController extends Controller
{
public function index(): Response
{
return new Response(Hash::make('pwd123'));
}
}
Instead of changing the default hash driver in the hashing.php
configuration file, a custom driver can be specified dynamically at runtime, such as:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Hash;
class TestController extends Controller
{
public function index(): Response
{
return new Response(Hash::driver('md5')->make('pwd123'));
}
}
The 1 Comment Found
Thanks it was very useful
Leave a Comment
Cancel reply