Skip to content

Instantly share code, notes, and snippets.

@chasecmiller
Last active February 3, 2021 17:24
Show Gist options
  • Save chasecmiller/eab970b54971e7ef7478cbfa380516d6 to your computer and use it in GitHub Desktop.
Save chasecmiller/eab970b54971e7ef7478cbfa380516d6 to your computer and use it in GitHub Desktop.
A laravel trait for setting passwords with automatic hashing.
<?php
namespace App\Traits;
use Illuminate\Support\Facades\Hash;
/**
* Trait HasPasswordAttribute
* @package App\Traits
*/
trait HasPasswordAttribute {
/**
* Set a password on the model. Automatically hash ( Bcrypt only ) if necessary
* @param string $in
*/
public function setPasswordAttribute(string $in) : void {
if (!$in) {
$this->attributes['password'] = '';
} else if (strpos($in, '$2y$') === 0 && strlen($in) == 60) {
$this->attributes['password'] = $in;
} else {
$this->attributes['password'] = Hash::make($in);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment