Created
May 7, 2022 21:00
-
-
Save jhavenz/7981141710143b1604a53089b69cbbd0 to your computer and use it in GitHub Desktop.
HasHashedPassword trait, generally for User model
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Models\Traits; | |
use Illuminate\Database\Eloquent\Model; | |
use Illuminate\Support\Facades\Hash; | |
/** | |
* @mixin Model | |
*/ | |
trait HasHashedPassword | |
{ | |
abstract public function getPassword(): string; | |
protected static function bootHasHashedPassword(): void | |
{ | |
static::saving(function (self $model) { | |
$model->hashPassword(); | |
}); | |
} | |
public function hashPassword (): static | |
{ | |
if (! $this->passwordIsHashed()) { | |
$this->setAttribute(self::PASSWORD, | |
Hash::make($this->getPassword()) | |
); | |
} | |
return $this; | |
} | |
public function passwordIsHashed (): bool | |
{ | |
return is_string($value = $this->getPassword()) && | |
strlen($value) >= 6 && | |
substr($value, 0, 5) === substr(Hash::make('foobar'), 0, 5); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment