Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mstarkey's avatar

Using bcrypt for password hashing

I am trying to create a function to add users to my system using name , email, start_date and password.

I can save all the data to the database row but cannot for the life of me hash the password using bcrypt, it should be relatively easy but i am missing something.

public function store(UserRequest $request, User $user)
    {
        $user->create($request->all());
        return redirect('admin/users');
    }

As you can see I have a store function but need to add the password hashing to it. any pointers please?

0 likes
4 replies
thomaskim's avatar
Level 41

@mstarkey There are two popular ways of doing this. Choose one of the following methods. In other words, don't combine the two methods.

  1. When you create your user, change the create function to something like this:
User::create([
    'name' => $request->name,
    'email' => $request->email,
    'password' => bcrypt($request->password),
    'start_date' => $request->start_date
]);
  1. Some people don't like having to specify all the attributes. If you like to keep your way of doing things where you just put $request->all(), then keep that and do this instead. Go to your User model and add this:
public function setPasswordAttribute($password) {
    $this->attributes['password'] = bcrypt($password);
}

This will automatically hash the password whenever you are setting the user's password.

1 like
helmerdavila's avatar

Try

...
$request['password'] = bcrypt($request->input('password'));
$user->create($request->all());
...
2 likes
tangoG's avatar

You can do this

$user->create([
        'name' => $request->input('name'),
        'email' => $request->input('email'),
        'password' => bcrypt($request->input('password')),
    ]);
1 like
mstarkey's avatar

Thank you all for your solutions, I went with the first model based solution as this fitted best with how I wanted the controller and model used, I also learned something from all the solutions, so once again thanks for your time it so very much appreciated.

1 like

Please or to participate in this conversation.