How to create a Laravel package
JhumanJ • February 16, 2021laravel
In this blog post I will explain how I created a Laravel package to authenticate users without using passwords.
Why I created a package
I have been working with Laravel for more than 5 years now, so I've used hundred of packages. Many of them were from the famous Spatie company, many others were from other individual contributors. While working on Moovino, I needed a package to authenticate users from links we sent in emails. This allows us to be a passwordless website. The package I found to do this is laravel-passwordless-login by grosv.
This package works as follows: - You use it to generate a signed link - You send the link to your user - The user clicks the link, triggering the controller provided by the package. The controller authenticates the user thanks to the url parameters (if signature is valid) and redirects the user to the intended page.
Unfortunately, because it uses a redirect mechanism, we cannot add custom GET parameters to the url. My use case was to track the links sent without Google Anlytics utm parameters. I could have added the utm params to the redirect target url, but it would cause some issues as utm parameters shouldn't be used with internal website navigation.
My solution to avoid this issue was to use a middleware instead of a controller + redirect. Thanks that mechanim, the user would be authenticated via the url, without being redirected. Which means that I could also add extra GET parameters that would be part of the signed url.
Let's see what I used to create this package.
I had never created a package before so I was starting from scratch. Here is how I did it:
- I created a package using Spatie's package template. It is very
easy to do so from Github. I then cloned the package locally, and followed the Readme to set up everything.
- Follow this guide from
Laravel news to figure out how to checkout and modify packages locally.
- I used laravelpackage.com a lot, it's a very valuable resource.
- In order to write tests for the package I needed to have some routes. But I didn't want to define any in the package,
as it's not the purpose of the package. I found about Orchestral Testbench
that is specifically designed for package testing. You can see how I used it here (check the
- Then it was just me coding and testing !
- Finally, I followed the publishing a package guide from laravalpackage.com
And that's pretty much it!
It was really interesting to create my own package after all these years of using other's packages. I took me less than a day, mostly because the Signed Auth Middleware package was very strongly inspired by grosv 's laravel-passwordless-login. It made me realize how convenient it was for code re-use. I really enjoyed working on that, and I will definitely be creating some more packages in the future.
If you have an issue creating your own package, or if you're just interested in my work, follow me on twitter: @JhumanJ.