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

davy_yg's avatar
Level 27

query

What does this query means?

 $query = Products::query();
0 likes
3 replies
tykus's avatar
tykus
Best Answer
Level 104

It gives you an Eloquent Builder instance to start a new query. You might use this approach if you conditionally build the query based on certain inputs, and/or other conditions, e.g.

// Get a query builder
 $query = Products::query();

// Conditionally constrain the query
if (auth()->user()->can('view_unpublished_products')) {
    $query->whereIn('published', [false, true]);
} else {
    $query->where('published', true);
}

// Finally, finish the query
$products = $query->get();

There is a when builder method which will allow you to conditionally constrain the query if a certain given condition is true if you prefer to chain, and the circumstances allow it.

davy_yg's avatar
Level 27

I forget to ask another question:

$query = Products::query();
    $men_products = $query->productMetas()->where('prod_meta_type', 1)->where('value', 1)->get();

(1/1) BadMethodCallException Call to undefined method Illuminate\Database\Query\Builder::productMetas()

I wonder why I get the error message?

tykus's avatar

You are at the level of the query builder (Illuminate\Database\Query\Builder) not the Eloquent builder so your scope/relation is not available.

Please or to participate in this conversation.