How To Get Current User ID In Laravel

How To Get Current User ID In Laravel

In this tutorial, we are learning How To Get Current User ID In laravel. Userid get a session store data to fetch and get user id.

Easy to get user id because Laravel is configured inbuilt authentication function, the Auth facade becomes useful for actions laravel get current user like grabbing the current logged in user id. Auth comes with various methods Laravel auth user, one of which is the id() the method, laravel get user id and this is where we can grab the authenticated user’s information like user id, user name, etc.

Use the following steps to get the ID of the current logged in user.

Laravel Get User Id Using Auth Facade

Step 1

Define the Auth facade for usage.

use Illuminate\Support\Facades\Auth;

Laravel Auth User Id Using Auth::check()

Step 2

This step, controller or similar, utilize the id() method of the laravel auth facade.

Note: At this point, Laravel Auth User Id the user must be already used authenticated laravel auth user, if there is a possibility of the user not being authenticated then not get user id, then please use the Auth::check() method to prevent exceptions being thrown to get laravel get current user.

Use the following code to populate the $id variable with the logged-in user ID.

$id = Auth::id(); 

And that is it, for this example, your user ID is 1, so the value of $id will now return 1.

Leave a Reply

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