SiNi_Si's avatar

Var sting for db::where($sting)

Need to make a very dynamic search I have tried..

$MyRequest = '[['type', 'For_Sale'],['live', '1']]';

$MyRequest = '[["type", "For_Sale"],["live", "1]]';

but fails $Items = Extra::where($MyRequest)->orderBy('display_order', 'ASC')->paginate(8);

Anyone know how to send a string to the ::where?

Thanks for looking Si

0 likes
3 replies
LaryAI's avatar
Level 58

To pass a string to the where method in Laravel's Eloquent ORM, you can use the whereRaw method. This allows you to write raw SQL expressions as part of your query.

Here's an example of how you can modify your code to achieve this:

$MyRequest = '[["type", "For_Sale"],["live", "1"]]';

$Items = Extra::whereRaw(json_decode($MyRequest))->orderBy('display_order', 'ASC')->paginate(8);

In this example, we use json_decode to convert the JSON string $MyRequest into an array. Then, we pass this array to the whereRaw method, which will treat it as a raw SQL expression.

Make sure that the JSON string is properly formatted with double quotes around the keys and values.

tykus's avatar
tykus
Best Answer
Level 104
$filters = collect(json_decode($MyRequest))
	->flatMap(fn ($filter) => [$filter[0] => $filter[1]])
    ->all();
/*
$filters = [
  "type" => "For_Sale",
  "live" => "1",
]
*/
$Items = Extra::where($filters)->orderBy('display_order', 'ASC')->paginate(8);
SiNi_Si's avatar

NICE

$MyRequest = ["type"=>"For_Sale", "live"=>"1",];

$Items = Extra::where($MyRequest)->orderBy('display_order', 'ASC')->paginate(8);

Works Thanks Tykus

Please or to participate in this conversation.