In this episode, we dive into a practical scenario where you don't know exactly which Eloquent model you'll be working with ahead of time—like when you're building a reusable package or letting users configure which model to use.
We start by saving the full class name of a model (like App\Models\Post
) in a config file, making it possible for end users to swap out which model your package uses. After fetching this value, you'll see it's just a string—so directly calling Eloquent methods like where('published', true)
won't work on it.
To get around this, we use Eloquent's static ::query()
method. By calling config('package.model')::query()
, you can start a query builder on whichever model class is provided—even when the model is only defined in your config file.
This approach makes your packages and apps more flexible and dynamic, perfectly suited for cases where the specific model class isn't fixed. You'll see the whole process in action, with a quick demo and explanation why it works.