Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel-5.1 inject the current logged in user to my controller

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?

like image 874
V4n1ll4 Avatar asked Aug 08 '15 09:08

V4n1ll4


Video Answer


1 Answers

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();
like image 53
Martin Bean Avatar answered Oct 20 '22 01:10

Martin Bean