Three ways to impersonate a user in Laravel
There comes a time when you want to log in or authenticate a user in your application manually. For instance, you have a functionality where admins can mimic a user to perform certain actions. Or you may just want to impersonate a user for testing purposes.
There are three ways Laravel lets you do this.
Login using user object
Using the Auth::login()
method, you can log in as a user using the user object.
use App\Models\User;
use Illuminate\Support\Facades\Auth;
$user = User::find(1);
// Logs in user with a session cookie
Auth::login($user);
// Logs in user with a permanent cookie
Auth::login($user, true);
Login using User ID
You can also log in as a user with a User ID using the Auth::loginUsingId()
method.
use Illuminate\Support\Facades\Auth;
// Logs in user with a session cookie
Auth::loginUsingId(1);
// Logs in user with a permanent cookie
Auth::loginUsingId(1, true);
Login without session or cookie
If you want to log in as a user without a session or cookie, you can use the Auth::onceUsingId()
method.
use Illuminate\Support\Facades\Auth;
Auth::onceUsingId(1);
Like this article?
Buy me a coffee👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.