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

stefan7's avatar

Query with whereHas

Hi, I need a query where I can insert the table-name in a flexible way and query should return all products that are connected with exporter (many to many). I was wondering why this is not working

        $products = DB::table('products')->whereHas('exporters', function (Builder $query) use($exporterId) {
            $query->where('exporter_id', '=', 1);
        })->get();

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'has' in 'where clause' (SQL: select * from products where has = exporters)

Whereas this works:

        $products = Product::whereHas('exporters', function (Builder $query) use($exporterId) {
            $query->where('exporter_id', '=', 1);
        })->get();

How can I get the first query to work? Thank you

0 likes
2 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

whereHas is eloquent only, but you can try whereExists instead

https://laravel.com/docs/6.x/queries#where-exists-clauses

If you need to use whereHas you can resolve the model dynamically (notice it is now a string)

$products = resolve('App\Product')- >whereHas('exporters', function (Builder $query) use($exporterId) {
            $query->where('exporter_id', '=', 1);
        })->get();
stefan7's avatar

Thank you, did not know about the resolve-helper.

Please or to participate in this conversation.