1

I make validation form registration using Laravel 9 and now I want to add correct data to database. This is my code in controller

public function store(RegistrationRequest $request)
{
    return redirect(
        route(
            'index.store',
            ['registration' => User::create($request->validated())]
        )
    );
}

But my problem is that I want to insert to database hash password. In model I have function which hash password but I don't know how to insert to database.

class User extends Model
{
use HasFactory;

protected $fillable = [
    'login', 'password', 'email'
];

public function opinions()
{
    return $this->hasMany(Opinion::class);
}

public function setPassword($value)
{
    $this->attributes['password'] = bcrypt($value);
}

}

I will gratefull if some help me how resolve this problem.

2
  • Did you add password to fillables array? Commented Jan 3, 2023 at 22:42
  • @BilalMaqsood Yes I add password to fillables, I modified my code and show all User model Commented Jan 3, 2023 at 22:46

1 Answer 1

1

Since you are using laravel 9 you have two option to store hashed password .Add this mutator in model

protected function password(): Attribute
{
   return Attribute::make(
        set: fn($value) => bcrypt($value),
    );
}

Ref :defining-a-mutator

or older way is

public function setPasswordAttribute($value)
{
     $this->attributes['password'] = bcrypt($value);
}

Ref: Defining A Mutator

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.