Contact Us

9 Quick Tips for Auth in Laravel – Laravel News

Mobile App | January 9, 2021

August 25, 2020

Laravel has a great out-of-the-box Auth system, but surely we need to customize things here and there. For some of them, no need to look for external packages or write a lot of custom code, let’s explore what interesting abilities are hiding under the hood of Auth.

Tip 1. Auth::routes() Parameters

We all probably know the method Auth::routes() that comes from the Laravel UI package (before Laravel 7, it was included in the core).

But did you know it may accept an array of parameters to enable/disable certain Auth routes?

As of Laravel 7, here are possible parameters, with their default values:

Those parameters just enable or disable some routes.

To understand how they work, you can look at the file AuthRouteMethods in Laravel UI:

Tip 2. Laravel UI: Generate Controllers Only

The official documentation specifies this main way of using Laravel UI:

But what if you don’t need the visual UI? What if you’re creating only an API-based project, and you don’t have any front-end on the Laravel side?

You can still use Laravel Auth and its Controllers. Install Laravel UI package and run this:

It will generate only app/Http/Controllers/Auth contents, so you don’t need Blade/Vue files to use them.

See the implementation of this Artisan command in Github repository.

Tip 3. Re-Confirm Password for Important Settings

Have you ever maintained a Github repository, and tried to change its access settings? Then Github asks you to re-enter your password again, just to make sure it’s you.

Since Laravel 6.2, we also have that feature in the framework.

All you need to do is to add a Middleware called password.confirm to the route(s) that you want to protect.

Quoting Dries Vints from the official feature release article:

If you attempt to access the route, you will be prompted to confirm your password, similar to what you may have seen on other applications like GitHub.

Confirming the password will store a timestamp in the user’s session that lasts for three hours by default so users do not have to enter their password during that period again.

You may customize this duration using a new password_timeout configuration option in the auth configuration file._

Tip 4. Logout Other Devices

From Laravel 5.6, we have a separate method to automatically log out any other devices or browsers that are logged in with our account:

Typical usage of this would be to log out other devices when the current device is successfully logged in. To do that, we override a method authenticated() from a Trait AuthenticatesUsers.php, and put this into app/Http/Controllers/Auth/LoginController.php:

Also, don’t forget to activate one middleware AuthenticateSession in app/Http/Kernel.php file, which is commented out by default:

Redirect after Login/Register: Custom Logic

By default, both Laravel LoginController and RegisterController have the same property:

So you can specify what URL to redirect to after successful login/registration. The default value is in app/Providers/RouteServiceProvider.php:

How can you customize it?

First, you can change the value of that $redirectTo property, to some other constant, and maybe separately for Login and Registration.

But what if you have a more complex logic of dynamic redirect, that depends on a user role, for example?

You can create a method in those Auth Controllers, call it redirectTo(), and specify your conditions inside. That method will override any values of $redirectTo property.

See example:

Tip 5. Quickly Create New Users

What if you need to create one new user, and you don’t have a registration form ready?

Just open Laravel Tinker in your Terminal:

If you’re not familiar with Tinker, it’s a command-line tool to execute any Laravel/PHP code. So, inside of that, you can easily create a user, typing this Eloquent command and hitting Enter:

But, what if you need to create many users for testing, Like, 10, or 100, or 1000? No problem, we can use a Factory class that comes by default with Laravel, in database/factories/UserFactory.php:

These are default values for the “fake” user that we may create. To do that, we will generate a Seeder file:

Then, we open that generated file database/seeds/UsersSeeder.php and fill run() method with this:

To launch that, we need to run this command:

You can read more about database seeding in the official Laravel documentation.

Tip 6. Login with Email and/or Username

By default, Laravel users authenticate with email and password. But what if your identifier is not email? Some kind of username, for example.

You can change it easily by overriding one method from the AuthenticatesUsers.php trait.

Here’s the default value:

You can copy that into your LoginController.php and just change the value:

Let’s take one step even further. What if your users can log in with email OR username? So there’s an input field called “Email/username” and they can put in one or another.

Let’s add a “trick” to the same username() method from above. We check if the entered string is an email, otherwise, we treat it as a username. That check is a PHP function, not even Laravel.

Notice: don’t forget that in your login form, you need to change input type="email" to type="text"

Tip 7. Too Many Login Attempts: Customize Parameters

If you try to log in with invalid credentials more than five times within the same minute, you will get blocked, with a message Too many login attempts. Please try again in X seconds.

That block will be active for 1 minute, and it is unique to the user’s username/e-mail and their IP address.

You can customize those parameters:

Those two parameters are inside of a Trait ThrottlesLogins:

So, to override those, you may specify properties inside of your LoginController:

Tip 8. Registration: Disable Auto-Login

By default, a newly registered user is automatically logged in and redirected to the home page.

If you want to disable that and show some “success” page instead, without automatically creating a user’s session, here’s what you can do.

The original registration method is inside the Trait RegistersUsers:

So your goal is to override it in RegisterController and return a redirect to your new page, instead of logging in:

Tip 9. Login: Additional Check with Email/Password

What if you need some extra check, in addition to the default email and password? For example, you want to check if the user is active, or not banned.

You can add extra elements to credentials array, which is defined in the trait AuthenticatesUsers:

You just override this in LoginController and add whatever you want:

Notice: this is an interesting quick tip, but I would advise you to perform such extra check in a separate Middleware, then you could provide a more explicit error message to the user, instead of a default credentials error.

That’s it, these are the quick tips, but there’s much more to be extended with custom code and external packages. So, stay tuned for more articles to come on that topic!

This content was originally published here.