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

appyapp's avatar

Getting SQL query in a variable

        $products = Vacancy::statusId($request->query('status'))
            ->sellerId($request->query('seller'))
            ->categoryId($request->query('category'))
            ->locationId($selectedLocationId)
            ->get();

I can see in the debugbar on my local pc that a query is executed e.g. SELECT * FROM products WHERE status_id=2 AND seller_id=5 AND category_id=19;

How do I store this query in variable?

`$sql = $products->toSql(); (Obviously it throws error). What do I need to do here?

0 likes
8 replies
mmdar1's avatar

@appyapp After calling the get() function on the query builder instance toSql() won't work so store the SQL in the variable before calling get method.

appyapp's avatar

Do you know any other way to do it?

bugsysha's avatar
bugsysha
Best Answer
Level 61
$builder = Vacancy::statusId($request->query('status'))
            ->sellerId($request->query('seller'))
            ->categoryId($request->query('category'))
            ->locationId($selectedLocationId);

$query = $builder->toSql();

$products = $builder->get();

Please or to participate in this conversation.