Support the ongoing development of Laravel.io →
posted 8 years ago
Eloquent

I'm writing something that is performing an eloquent query on a model called Enquiry. The actual query I want to run will be built up dynamically based on input parameters.

To create the basic starting point, I'd like to retrieve the "base" eloquent query builder (Illuminate\Database\Eloquent\Builder) for my Enquiry model, e.g. the equivalent to SELECT * FROM enquiries.

I can't use Enquiry::all() since that actually runs the query, and I just want to return the builder, not run it.

Am I missing something?

        $enquiries = null; // I want to get the base builder here ....
        collect($keywords)->each(function($item) use (&$enquiries) {
            // So I can drop the first half of this "if" condition, and just "add" to the base
            if (!$enquiries) {
                $enquiries = Enquiry::whereHas('data', function($query) use ($item) {
                    $query->where('value', 'like', '%'.$item.'%');
                });
            } else {
                $enquiries->orWhereHas('data', function($query) use ($item) {
                    $query->where('value', 'like', '%'.$item.'%');
                });
            }
        });
Last updated 3 years ago.
0
Solution

For a static call to get the builder:

$builder = Model::query();

If you have a model instance:

$builder = $model->newQuery();

Model@query is just creating a new instance of the model and returning the call to newQuery().

0

Perfect - thanks!

0

Sign in to participate in this thread!

PHPverse

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.