Laravel Eloquent WithWhereHas Mixing with and whereHas using a scope

Image for post
Image for post

I was going with some places where I needed both the with and whereHas and using that in multiple places is not a good practice. So, I tried making that a model scope and reusing wherever needed.

I have also tried to pass dynamic relation, operators, and parameters, single value where parameters or array type so in case it can handle any condition.

What I did was created a model scope like the following:

If you need this scope everywhere in the model then what you do is create a base class model and extend your model with that base class model. Then you can use it everywhere you like.

You can customize it as per your need. Hope it helps you guys.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store