Laravel Auth is so easy

I love Laravel authentication. I was going to write a post about how to write a log out feature and it was meant to be this big thing but reall there isn’t much to it. I’ll paste and discuss my code and maybe we all learn something..

Logging in

public function store()
  //Log the user in
  $user = User::where('email', '=', Input::get('email'))->first();
  if (Auth::attempt(array('email' => Input::get('email'), 'password' => Input::get('password'))))
    Session::put('user', $user);
    return Redirect::to("/users/{$user->id}");
  } else {
    return Redirect::to("/login");

So what’s happening here is that we find the user using their email address and if we can authenticate using Laravel’s Auth::attempt function we put the user into the Session for later access and we redirect the user to their user profile. If the user does not authenticate then we redirect them to the login page.

Logging out

public function destroy()
  //Log the user out
  if (Auth::check())
    $user_id = Auth::user()->id;
    return Redirect::to("users/{$user_id}");
  } else {
    return Redirect::to("/");

When we want to log the user out I’m chosing to use the Auth::logout function because we logged the user in with the Auth::attempt function earlier. First we run the Auth::logout function and after that we run an Auth::check. If the user is still logged in then we get the user id from the authenticated session and redirect the user to their user profile. If the authentication check fails then we flush all data out of the Session because we stored a copy of the user in there and then we redirect the user to the root URL of the application.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

You May Also Like