Password reset for multiple tables in Laravel

Reset and recover password for multiple tables in Laravel

Laravel documentation is silent about this or gives or gives very little information. The necessity to have different sql tables for authentication, for example one for administration users and the other for visitors to the site or web application (api) is quite common. Resetting and recovering the password for these tables in Laravel should also be provided.

This guide will cover methods for the current versions of Laravel 8 - 9.

Faced with the task of recovering a password for several tables in Laravel, we had to spend a lot of time searching for solving this problem, the advices we found is either very outdated or completely wrong. Even in the well-known Laracasts, we were not given a reasonable explanation for this question.

If authentication for many tables in Laravel is solved using Guard, but for reset and recover the password we have to take a different approach.

But the solution to this problem exists and it is simple. We want to share it with you so that you save your time and effort.

Required Initial File Preparation

We assume that you have already created a second table based on Laravel's example (users), in the example we'll use a table called (admins).

If you have not created a model, then this must be done, for example, based on the existing (User), important note your model must include all namespaces and traits (User). In the example, we'll use the name for the model (Admin).

And a separate table for temporary storage (Token), for example, based on password_resets, the example uses the name admin_resets.

Accordingly, it is necessary to fill in at least one field of the table (Admin) to work with it, now the initial preparation is finished.

Addings guards, providers, passwords

Go to file path: config/auth.php

Find section (guards) and add:

Adding guards in Laravel

Go to section (providers) and add the following entries:

Adding providers in Laravel

Find section (passwords) tables for temporary storage (Token) will be specified here. You can also specify the maximum time after which (Token) will be deleted, by default (expire = 60 ) - one hour.

Adding password broker() in Laravel

Defining routes for reset and recover password of multiple tables in Laravel

For simplicity, an example taken from the Laravel documentation.

Need to add a method call (broker('admins')) it is highlighted in two places in the code. In parametr "broker" add the name that was defined in "passwords" in file (config/auth.php)

Define routes in Laravel 1
Define routes in Laravel 2
Define routes in Laravel 3
Define routes in Laravel 4
Define routes in Laravel 5

We can do this and many other works development of sites and applications on Laravel.

Author: Yuriy Lisenko