How to get current user id in constructor in laravel?

Member

by jasen , in category: PHP Frameworks , a year ago

How to get current user id in constructor in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dana , 10 months ago

@jasen 

In Laravel, you can access the current user ID in the constructor of a class by using the Auth facade to retrieve the authenticated user and then accessing the id property of the user object.


Here is an example of how to get the current user ID in the constructor of a class:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
use IlluminateSupportFacadesAuth;

class YourController extends Controller
{
    public function __construct()
    {
        $userId = Auth::id();
        // You now have the current user ID stored in the $userId variable
    }
}


Make sure to import the Auth facade at the top of your file in order to use it. This will allow you to access the current user ID in the constructor of your class.

Related Threads:

How to get the id of the current user in symfony?
How to get the id of current saved model in laravel?
How to get current user data only in laravel?
How to get the user id from laravel passport token?
How to get the 4 digit user id of a discord user?
How to check current user in laravel?