In this episode, we're diving into using Eloquent Observers within a Slim 3 application. If you're familiar with Eloquent observers in Laravel, you'll notice the setup here is a bit different due to Slim's structure. We start with a standard Slim 3 setup, using the CoCourse Slender package (link provided in the course), and assume you've already got Eloquent configured and running.
First, we walk through creating a basic Eloquent model for a Topic
, with the typical title and slug fields. We explore how, in Laravel, you'd usually configure an observer via a service provider, but here, because Slim doesn't have the same container and provider setup, we look for a simpler, more direct solution.
You'll learn how to override the model's boot
method and register a creating observer via closures. But, crucially, we run into an issue: Eloquent events won't work properly until we manually add an event dispatcher to Eloquent's Capsule Manager—something Laravel does automatically. We fix that by requiring illuminate/events
via Composer, then set everything up to get observers firing as expected.
Next, we refactor the observer code out of our model and into its own observer class for better organization. This way, using the observe()
method, you can keep your model definitions tidy, and easily manage multiple event hooks. Finally, we show that you can register observers anywhere in your app's bootstrap process, tailoring your structure however you like.
By the end, you’ll understand not just how to set up and use observers in Eloquent outside of Laravel, but also why the event dispatcher is essential and how to keep your codebase clean by separating logic. This video is packed with practical takeaways for integrating Eloquent functionality into Slim 3 projects!