How can I inject the current logged in user model to my controller?
For example, in my controller I currently have:
public function update(SaveAccountRequest $request)
{
$user = User::findOrFail(Auth::user()->id);
$user->first_name = $request->get('first_name');
$user->last_name = $request->get('last_name');
$user->email = $request->get('email');
if($request->has('password')) {
$user->password = Hash::make($request->get('password'));
}
$user->save();
return redirect('/admin/account')->with('success', 'Your details have been saved.');
}
But instead of having this line:
$user = User::findOrFail(Auth::user()->id);
It would be nice just to inject the User
model into my controller which loads in the already logged in user, so that I could us this instead:
public function update(SaveAccountRequest $request, User $user)
{
$user->first_name = $request->get('first_name');
$user->last_name = $request->get('last_name');
$user->email = $request->get('email');
if($request->has('password')) {
$user->password = Hash::make($request->get('password'));
}
$user->save();
return redirect('/admin/account')->with('success', 'Your details have been saved.');
}
How can I achieve this?
The Request
object (and in turn, any form request classes) have access to the currently authenticated user:
public function update(SaveAccountRequest $request)
{
$user = $request->user();
$user->first_name = $request->input('first_name');
$user->last_name = $request->input('last_name');
$user->email = $request->input('email');
if ($request->has('password')) {
$user->password = bcrypt($request->input('password'));
}
$user->save();
return redirect('/admin/account')->with('success', 'Your details have been saved.');
}
No need to inject any thing, use façades, or query the database.
Also, if your attributes are marked as fillable you could just mass-assign them, without having to assign each property on your User
model individually:
$user = $request->user()->fill($request->except('password'));
if ($request->has('password')) {
$user->password = bcrypt($request->input('password'));
}
$user->save();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With