0

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?

2
  • Why are you formatting the query functions as strings? Commented Jan 3, 2018 at 15:12
  • @JimWright I didn't realize I had a better option! Commented Jan 3, 2018 at 15:16

1 Answer 1

1

I'm not 100% sure on exactly what you're asking, but I think the following will work for you.

$batch = MyModel::whereHas('asset', function ($query) use ($settings){
    if(isset($settings->new)){
        $query->where('created_at','>',Carbon::now()->subMonths(1));
    }
    if(isset($settings->long)){
        $query->where('lengthD','Long');
    }
    if(isset($settings->short)){
        $query->where('lengthD','Short');
    }
    if(!isset($settings->new)&&!isset($settings->long)&&!isset($settings->short)){
        $query->where('id','>',0);
    }
})->orderBy('id', 'desc')->take(20)->get();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.