Custom guard for your Laravel module

Again I’ll be writing about the Laravel modules package. This time it’s about adding a custom guard for your Laravel module. It’s not a very common requirement, but it happens from time to time that a custom login is required.


Before we begin we’ll make two configuration files in our module. We will add the files guard.php …

… and provider.php …

… to the Modules\Admin\Config  folder. With these configurations in place, we move over to the AdminServiceProvider.php file. Here we will modify the method name  registerConfig() .

You can create create your own method if you want, but for simplicity we will just modify the existing method. Out of the box the method looks like this

We need to add two more calls to the mergeConfigFrom() method, to load in the two configs we created above. Our modified method should look like this

Now, if we look at the ourput of  print_r(config('auth'));die(); we should something like this

I replaced everything not related to what we’ve added, to save some space.

Setting up the model

When we have the configuration in place, the next step is to set up the User model. First we run the artisan command to create it

This will create the file User.php  inside the folder  Modules\Admin\Entities. Finally we just need to replace Illuminate\Database\Eloquent\Model  with Illuminate\Foundation\Auth\User to make it compatible with native Laravel Auth.

That’s it

To use this newly created guard just call it as you would with the default Laravel auth middleware.

Now you can protect any route with this new custom guard. This is very handy if you make standalone packages which requires its own set of guards and providers.

If you find my posts helpful, feel free to buy me a coffee, and if you have any suggestions or questions, feel free to leave me a comment below or send me a message on Twitter