DEV Community

Ariel Mejia
Ariel Mejia

Posted on • Updated on

Auto login with Laravel on development

In development could be annoying to add credentials when we are showing or testing the ui in the browser all the time, here a little tip:

Add a User seeder with your development user

database/seeders/UserSeeder.php

User::factory()->create([
    'name' => 'your name',
    'email' => 'your@email.com'
]);
Enter fullscreen mode Exit fullscreen mode

You can add alternatively a password but it is not necessary, the default user factory adds a password for all users as string "password" so you can stay with this for all development users.

Add a route

routes/web.php

Route::get('/dev-login', function() {
    abort_unless(app()->environment('local') ,403);

    auth()->login(User::first());

    return redirect()->to('/');
})->name('dev-login');
Enter fullscreen mode Exit fullscreen mode

Add a link on your login view

<a href="{{ route('dev-login') }}">Dev Login</a>
Enter fullscreen mode Exit fullscreen mode

Auto login using AuthServiceProvider

You can also set a default authenticated user with this code in AuthServiceProvider:

public function boot()
{
    if($this->app->environment('local')) {
        $this->app['auth']->setUser(new User([
            'name' => 'John Doe',
            'email' => 'john@doe.com'
        ]));
    }
}
Enter fullscreen mode Exit fullscreen mode

If you are working with Jetstream

The dashboard and other pages use some middlewares with current team id, so you must need to create a user with a personal team first and pass the user as the authenticated user

On a UserSeeder or DatabaseSeeder class

User::factory()->withPersonalTeam()->create();
Enter fullscreen mode Exit fullscreen mode

Then migrate & seed the database:

php artisan migrate:fresh --seed
Enter fullscreen mode Exit fullscreen mode

Then modify a little bit the AuthServiceProvider:

public function boot()
{
    if($this->app->environment('local')) {
        $this->app['auth']->setUser(User::first());
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
rvxlab profile image
RVxLab • Edited

Why not use a Middleware for this and conditionally load it in a ServiceProvider?

On top, I really wouldn't return a 403 here. In most circles you'd give away that there's something there. I'd return a 404 instead.

Collapse
 
arielmejiadev profile image
Ariel Mejia

its another approach I just imagine a login button to make it but it sound cleaner on authServiceProvider, definitely another interesting approach