This is how I would make such a function Controller code
public function store(RegistrationStoreRequest $request){
$user = User::create($request->validated());
Auth::login($user);
return redirect()->home();
}
This is my Request form code
public function rules()
{
return [
'name' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed'
];
}
CodePudding user response:
You have two options:
- Create a value mutator:
public function setPasswordAttribute($value) {
$this->attributes['password'] = Hash::make($value);
}
however you need to ensure you never prehash the password.
- Hash in controller
public function store(RegistrationStoreRequest $request){
$user = User::create(array_merge(Arr::except($request->validated(), 'password'), [ 'password' => Hash::make($request->password) ]));
Auth::login($user);
return redirect()->home();
}
CodePudding user response:
The easiest and most clean way is to use a custom cast for password field, first create UserPasswordCast.php class:
<?php
//app/Casts/UserPasswordCast.php
namespace App\Casts;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Support\Facades\Hash;
class UserPasswordCast implements CastsAttributes
{
public function get($model, $key, $value, $attributes)
{
return $value;
}
public function set($model, $key, $value, $attributes)
{
//return hashed value
return Hash::make($value);
}
}
Suggested location:
app/Casts/UserPasswordCast.php
Then update your 'user' model to use this cast, add "$casts" array or update it if existed:
use App\Casts\UserPasswordCast;
...
protected $casts = [
...
'password' => UserPasswordCast::class
];
That's it, you don't have to worry about password again
Just save your user model as it:
public function store(RegistrationStoreRequest $request)
{
$user = User::create($request->validated());
Auth::login($user);
return redirect()->home();
}
For more info please check:
CodePudding user response:
=>create method function add in User.php(Model).
public static function create($user, $request)
{
if (isset($request->name)) {
$user->name = $request->name;
}
if (isset($request->email)) {
$user->email = $request->email;
}
if (isset($request->password)) {
$user->password = bcrypt($request->password);
}
if (isset($request->confirmpassword)) {
$user->confirmpassword = $request->confirmpassword;
}
$user->save();
return $user;
}
=>New user create with validate your all request field.
public function store(RegistrationStoreRequest $request){
$user = User::create(New User,$request);
Auth::login($user);
return redirect()->home();
}
Please try this code it is working.