Laravel Authentication

Author: Al-mamun Sarkar Date: 2020-07-18 05:32:09

In this lesson, I will show you how to manage authentication on laravel applications. Showing codes for login in, checking routes, Log out, Registration. 

 

Manually Authenticating Users:

public function authenticate(Request $request)
{
    $data = $request->only('email', 'password');

    if (Auth::attempt($data)) {
        return redirect()->intended('dashboard');
    }
}

 

Additional Conditions:

if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) {
    // The user is active, not suspended, and exists.
}

 

Remembering Users:

if (Auth::attempt(['email' => $email, 'password' => $password], $remember)) {
    // The user is being remembered...
}

 

Other Authentication Methods:

// Login via user model's object
Auth::login($user);

// Login and "remember"
Auth::login($user, true);

// Login vai user id
Auth::loginUsingId(1);

// Login and "remember"
Auth::loginUsingId(1, true);

 

 

Checking Authentication:

if (Auth::check()) {
    // The user is logged in...
}

 

Checking Auth on Routes:

Route::get('route-path', function () {
    // Only for authenticated users
})->middleware('auth');

 

Protect on controller constructor:

public function __construct()
{
    $this->middleware('auth');
}

 

For Redirecting Unauthenticated Users Update redirectTo on Authenticate Middleware:

app/Http/Middleware/Authenticate.php

 

Logging Out User:

use Illuminate\Support\Facades\Auth;

Auth::logout();