How to get current user id in constructor in laravel?

Member

by jasen , in category: PHP Frameworks , 5 months ago

How to get current user id in constructor in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dana , 5 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.