Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vinodjoshi's avatar

How to Apply Same Query to Multiple Eloquent

Hi Guys,

I have 4 tables product, customers, salesmen and invoice

And i am doing some filter like Include customer, Include Salesmen Include customer, Exclude Salesmen

In my case the query is same all time but i need to apply it to different Eloquent every time.(Product Model with Invoice table, Customers Models with Invoice Table, Salesmen Model with Invoice Table)

Is there any way to make our query as constant or common so i can apply that to different Model.

Thanks

0 likes
4 replies
kfirba's avatar

@vinodjoshi Hey

Are you talking about a query scope? If that so, simply create a trait and use it in your models.

trait YourTraitName
{
    public function scopeSomeScope($query, $parameter)
    {
        return $query->where(...);
    }
}

Now in your models:

class Customer extends Model
{
    use YourTraitName;
}
class Invoice extends Model
{
    use YourTraitName;
}

And use the scope wherever necessary:

Customer::someScope($argumentIfNeeded)->get();
Invoice::someScope($argumentIfNeeded)->get();
vinodjoshi's avatar

Hi @kfirba It works perfect with Laravel Eloquent,

But Does this works for Query Builder ?

Please or to participate in this conversation.