🎓 A1Learner
🔍
0 of 50 lessons completed

Laravel Authentication Basics

Authentication checks who a visitor is. It matches an email and password against a stored user.

Who is visiting

A guest sees one word, and a logged in user sees a greeting.

if (Auth::check()) {
    return 'Hello, '.Auth::user()->name;
}

return 'Guest';

Logging in

A right password logs the visitor in.

if (Auth::attempt($request->only('email', 'password'))) {
    return 'Logged in as '.Auth::user()->name;
}

Logging out

Auth::logout ends the login.

Auth::logout();

return 'Logged out';

Example

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;

Route::post('/l43/login', function (Request $request) {
    if (Auth::attempt($request->only('email', 'password'))) {
        return 'Logged in as '.Auth::user()->name;
    }

    return response('Login failed', 401);
});

Key points

  • Authentication: the check that proves who a visitor is.
  • Use Auth::attempt to log a visitor in with an email and password.
  • Use Auth::user to read the logged in user.
  • Use Auth::check to ask if a visitor is logged in.

In this example, the route reads the email and password from the request. Auth::attempt checks them against a stored user. A match returns a greeting with the user name. A miss returns a Login failed response. Authentication checks who a visitor is. Send a POST request with the right password to see the output.

Note

A failed login must not say which part was wrong.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does Auth::attempt do?