What is the difference between boot and register in service providers

Where do I put this code?

Joel Clermont
Joel Clermont
2024-01-09

Every Laravel service provider starts with two methods: boot and register. It's important to know what the difference is, so you know the right place to put your code.

The key difference is when the methods run.

The register method is called earlier and is run independently of any other service providers. The main purpose of this method is to bind things into the container. One other thing I've used it to for is to dynamically register other service providers (like Telescope) based on the environment.

If you try to put any other code in there that relies on services coming out of the container, they may not have been registered yet, so you could get an error.

On the other hand, the boot method is called after all service providers have finished registering. Because of that, you are safe to use any application services here, with full confidence they'll be ready to use. So this is where you want to put most of your code, like macros, Blade directives, gates, view composers, and so on.

Here to help,

Joel

P.S. If you haven't seen it yet, download our free book with other practical Laravel tips.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼

Level up your Laravel skills!

Each 2-minute email has real-world advice you can use.