In this episode, we take a look at a practical pattern for handling Eloquent models in Laravel that have a notion of being "live" or not—think published/unpublished articles, visible/invisible posts, that kind of thing.
We start by creating a basic Article
model and add a boolean live
column to the migration with a default value of false
so that new articles start off as not live by default. Then, to make our model "live aware" and keep our code clean and DRY, we extract a query scope into a trait called LiveAware
. This trait can be reused across any models that need this kind of live/not-live functionality.
After covering the basics, we explore different ways to restrict access to non-live models when showing them on the frontend. First, we do a classic (but a bit messy) if
check inside the controller, but quickly see why that's not ideal for maintenance or clean code. Next, we go over adding a global scope to the model, but explain the downsides of that (admin panels, for example, might need to see non-live items too).
Finally, we land on what I think is the best solution: a dedicated IsLive
middleware that checks if the model is live (using root model binding), and bails out with a 404 if not. We make it reusable and easily configurable via middleware parameters—so you can use it for any model that uses the LiveAware
trait. This keeps controllers tidy and makes it easy to customize which routes need this constraint.
So, you'll walk away from this video with a simple, scalable solution for managing "live" models in Laravel, with all the pros and cons of each approach explained along the way.