I am trying to retrieve the raw value of an attribute in an Eloquent model on saving event, before any casts are applied. Tried this with Laravel's built-in hashed cast (see method in trait HasAttributes::setAttribute() which calls HasAttributes::castAttributeAsHashedString()) and with my own cast:
<?php
namespace App\Casts;
use Illuminate\Contracts\Database\Eloquent\CastsInboundAttributes;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Hash;
class Hashed implements CastsInboundAttributes
{
public function set(Model $model, string $key, mixed $value, array $attributes): string
{
return $value !== null && password_get_info($value)['algo'] === null ? Hash::make($value) : $value;
}
}
then, in the model, I try to retrieve the original unhashed value with this trait:
<?php
namespace App\Models\Traits;
use Illuminate\Database\Eloquent\Model;
/** @mixin Model */
trait HasPassword
{
public static function bootHasPassword(): void
{
static::saving(function (self $model) {
if ($model->isDirty('password')) {
$model->password_changed_at = now();
}
dump($model->getRawOriginal('password'));
// ... and do some more fancy things with the plaintext password, e.g. zxcvbn password strength calculation
});
}
}
but getRawOriginal() returns the already hashed value, no matter if I use 'hashed' cast (Laravel built-in) or my own implementation App\Casts\Hashed (which I thought would get applied later then HasAttributes::setAttribute()). How could this be done without using a mutator as a workaround?