Create Method on User Model (bcrypt)

After looking at the new laravel version 5.4 i notice when using "$user = User::create(request(['name', 'email','password']));" the password isnt automatically bcrypt the password, is it me, or isnt the password hashed by default on the model create method? I dont remember, but isnt supposed the method "create" already do this?


Solution 1:

In User Model you need to add below function, for default password encrypted.

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

Solution 2:

As stated in the Laravel Docs

If you are using the built-in LoginController and RegisterController classes that are included with your Laravel application, they will automatically use Bcrypt for registration and authentication.

If you use RegisterController.php that is shipped in Laravel you don't need to Hash password manually else you need to use

 return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']), //<==encrypt here
        ]);

Check the register Controller here:

https://github.com/laravel/laravel/blob/master/app/Http/Controllers/Auth/RegisterController.php#L63

Solution 3:

Try out the following.

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Illuminate\Support\Facades\Hash;

use App\User;

class RegistrationsController extends Controller {

public function store()
{
    //validate the form
    $this->validate(request(),[
        'name'=> ['required', 'string', 'max:255'],
        'email'=> ['required', 'string', 'email', 'max:255', 'unique:users'],
        'password'=>['required', 'string', 'min:4', 'confirmed'],
    ]);

    //create and save the user

        $user =User::create([
       'name'=>request('name'), 
       'email'=>request('email'),

        //hash your password 

       'password'=>Hash::make(request('password'))
       ]);

    //sign in the user
    auth()->login($user);

    //redirect to the homepage
     return redirect()->home();
}

}