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'
];
}
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();
}
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:
https://laravel.com/docs/8.x/eloquent-mutators#custom-casts
=>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.
Related
How to pass a variable($test) from store to index? because I would like to display a variable in my index.blade
public function index()
{
return view('users.index', [
'users' => User::all()
]);
}
public function store(Request $request)
{
$user = new User($request->all());
$user->save();
$test = "test";
return redirect('users');
}
To resolve your problem you may edit your code like below:
index function:
public function index($test=null)
{
return view('users.index', [
'users' => User::all(),
'test' => $test
]);
}
store function:
public function store(Request $request)
{
$user = new User($request->all());
$user->save();
$test = "test";
return redirect(route('users.index', compact('test')));
}
N.B: for storing your user I don't recommend to you mass assignment (new User($request->all())) when you create a new user especially if you have a password or token to store there.
Hey guys so I made a route:
Route::get('/dashboard/{user}', [DashboardController::class, 'show'])->name('dashboard.show');
My controller is
public function show($id)
{
return view('dashboard.profile')->with('name',User::where($id));
}
How do pass it into the view? so I get only data from the current user / userid
You can simplify it to this by using route model binding:
public function show(User $user)
{
return view('dashboard.profile', [ 'user' => $user ]);
}
You Can Do This:
public function show(User $user)
{
return view('dashboard.profile', [ 'user' => $user ]);
}
Or :
public function show($id)
{
$user = User::findOrFail($id);
return view('dashboard.profile', [ 'user' => $user ]);
}
Or :
public function show($id)
{
$user = User::where("id",$id)->first();
return view('dashboard.profile', [ 'user' => $user ]);
}
If You Need Authenticated user use :
auth()->user
I want to apply soft delete in laravel5.4 inbuilt reset password. Due to duplicate email of soft delete deleted email password is change but not the correct one. I am getting stuck to where apply deleted should be null instead of email checking only. that's why it fetches the deleted record insted of correct one. My reset password controller is given below. Please check my reset controller & suggest any solution please.
class ResetPasswordController extends Controller
{
use ResetsPasswords;
protected $redirectTo = 'member/welcome';
public function showResetForm(Request $request, $token = null)
{
return view('frontend.member.auth.passwords.reset')->with(
['token' => $token, 'email' => $request->email]
);
}
public function reset(Request $request)
{
$this->validate($request, $this->rules(), $this->validationErrorMessages());
$response = $this->broker()->reset(
$this->credentials($request), function ($user, $password) {
$this->resetPassword($user, $password);
}
);
return $response == Password::PASSWORD_RESET
? $this->sendResetResponse($response)
: $this->sendResetFailedResponse($request, $response);
}
protected function rules()
{
return [
'token' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed|min:8|regex:/^.*(?=.{3,})(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[\d\x])(?=.*[#!$#%^*()-_]).*$/',
];
}
/**
* Get the password reset validation error messages.
*
* #return array
*/
protected function validationErrorMessages()
{
return [
'password.regex' => 'The password must contain at least one uppercase, one lowercase, one number and one special(#!$#%...) character.'
];
}
protected function resetPassword($user, $password)
{
$password = app('hash')->needsRehash($password) ? Hash::make($password) : $password;
$user->forceFill([
'password' => $password,
'remember_token' => Str::random(60),
])->save();
$this->guard()->login($user);
}
public function broker()
{
return Password::broker('members');
}
protected function guard()
{
return Auth::guard('web_member');
}
}
Please help thanks in advance.I am new to laravel please help.
Just need to pass the correct user to resetPassword() function like
public function reset(Request $request)
{
$this->validate($request, $this->rules(), $this->validationErrorMessages());
$response = $this->broker()->reset(
$this->credentials($request), function ($user, $password) {
$user = User::where('email', $user->email)->whereNull('deleted_at')->first();
$this->resetPassword($user, $password);
}
);
return $response == Password::PASSWORD_RESET
? $this->sendResetResponse($response)
: $this->sendResetFailedResponse($request, $response);
}
I upgraded:
"tymon/jwt-auth": "0.5.*",
from a very old version, and it seems like the API has changed. I managed to fix the login, using:
public function login(Request $request)
{
$credentials = $request->only(['username', 'password']);
$validator = Validator::make($credentials, [
'username' => 'required',
'password' => 'required',
]);
if($validator->fails()) {
throw new ValidationHttpException($validator->errors()->all());
}
if (!$token = auth()->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
$user = auth()->user();
$user->ip_address = $request->ip();
if ($request->device_token)
$user->device_token = $request->device_token;
$user->save();
$data['token'] = $token;
$data['email'] = $user->email;
return response()->json($data);
}
So my login work, but all API's that required the token - fail now.
Example of API that fail:
class UserController extends Controller
{
public function __construct()
{
// $this->middleware('auth:api', ['except' => ['login']]);
}
public function enterWorld(Request $request)
{
$token = $request->input('token');
$user = JWTAuth::toUser($token);
return $user;
}
Any idea how to convert the token from the request to the user with the new API?
I couldn't find any docs about it.
I tried:
return response()->json(auth()->user());
but in this API it return empty array. only in login it works.
Try the following:
$user = JWTAuth::setRequest($request)->user();
You may also explicitly set the guard when using the following syntax:
// pass the guard in to the auth() helper.
return response()->json(auth('jwt')->user());
In my first controller, I guess, I use the most basic way of creating a user password
EmployeeController
public function store(Request $request){
$user = User::create(array(
'username' => $request->username,
'password' => Hash::make($tempPassword = Str::random(8)))
);
$employee->user()->associate($user);
$employee->save();
}
Shen it comes to checking the password with Hash::check() in the second controller it always fails
ResetPasswordController
public function index(ResetPasswordRequest $request){
$request->validated();
$emp = Student::find($request->id);
if ($emp->user->checkCredentials($request->password)) { //always false
}
}
However, if update password in the same controller (just for testing) it works just fine
ResetPasswordController
public function index(ResetPasswordRequest $request){
$request->validated();
$emp = Student::find($request->id);
$emp->user->update(['password' => Hash::make('abc')]);
if ($emp->user->checkCredentials('abc')) { //...true
}
}
User
public function checkCredentials($password){
return (Hash::check($password, $this->password)) ? true : false;
}
I don't change the app key between creating and checking the user passwords. Any ideas where else should I look?