Skip to content

Instantly share code, notes, and snippets.

@jhavenz
Created May 7, 2022 21:00
Show Gist options
  • Save jhavenz/7981141710143b1604a53089b69cbbd0 to your computer and use it in GitHub Desktop.
Save jhavenz/7981141710143b1604a53089b69cbbd0 to your computer and use it in GitHub Desktop.
HasHashedPassword trait, generally for User model
<?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