I am trying to take JSON sent to my Laravel server and return the results of an Eloquent query string which is itself constructed based on the JSON that is being sent. I plan to chain together multiple where
/whereHas
statements to achieve this, but so far I am stuck on the first and wondering if this is possible.
Code:
if(isset($settings->new)){
$assetQuery = "where('created_at','>',".Carbon::now()->subMonths(1).")";
}
if(isset($settings->long)){
$assetQuery = "where('lengthD','Long')";
}
if(isset($settings->short)){
$assetQuery = "where('lengthD','Short')";
}
if(!isset($settings->new)&&!isset($settings->long)&&!isset($settings->short)){
$assetQuery = "where('id','>',0)";
}
$batch = MyModel::whereHas('asset',function ($query) use ($assetQuery){return $query->$assetQuery;})
->orderBy('id', 'desc')->take(20)->get();
$settings
is a json_decode
representation of my JSON. It will only have one instruction where in comes to the $assetQuery
. As you can see, if it fails to have any of these instructions it will pick all of them (where('id','>',0)
).
My issue is I can't seem to append the $assetQuery
string to the $batch
Eloquent line. How can I do this so I can string together variable queries?
I did see this: Laravel Advanced Wheres how to pass variable into function?
But in that case the variable was being used in one very small section of the query, not for the whole query string. Maybe I need to move my conditionals within the function ($query)
function?