How to Implement Guest Login Functionality in Laravel
Thank you for your continued support.
This article contains advertisements that help fund our operations.
Table Of Contents
⇨ Click here for the table of contents for Laravel articles
This article summarizes how to implement guest login functionality in Laravel.
Implementation Environment
Laravel Framework 8.*
Laravel Mix v6.0.*
Prerequisites
The guest user to be logged in is already in the DB.
Specifications
Register the guest user in advance.
This time, we will proceed with the ID of the generated guest user as 1.
Implementation Method of Guest User Login Function
Create Routes
web.php
// Controller generation, use statement is omitted.
Route::post('/guest-login', [ LoginController::class, 'guest'])->name('guestLogin');
Write in the Controller
LoginController.php
use Auth;
use App\Models\User;
<!-- ~~~~~ -->
public function guest()
{
$guestUserId = 1; // Set guest user's ID as 1
$user = User::find($guestUserId);
Auth::login($user);
// Redirect to where you want to after login
// return redirect()->route('home');
}
Add Button on the Display Side
POST to the created route.
It may be fine to use GET for this type of function, like in a portfolio, but this time we are using POST.
<form methods="POST" action="{{ route('guestLogin') }}">
@csrf
<button>Guest Login</button>
</form>
Summary
That's all. Hope this can be helpful for someone.
This blog is supported by ad clicks. Thank you.
Thank you and goodbye!
Popular Articles