3

I am trying to filter my results. For this i have following query:

$destinations = $request['destinations'];
        if($request->has('destinations'))
        {
            $trips = Trip::where('status','=',1)->whereHas('destinations', function($q) {
            $q->where('destinationsid', '=', $destinations);
            })->get();
        }else{
             echo "No destination provided";
        }

But I'm getting undefined variable $destinations. If i replace $destinations with any id (6) it shows results. I have also tried to echo $destinations outside the query, it is returning array. What is wrong here? Can anyone help me?

4 Answers 4

3

Try to add the use($destination) after function($q):

$destinations = $request['destinations'];

if($request->has('destinations'))
{
     $trips = Trip::where('status','=',1)->whereHas('destinations', function($q) use($destinations) {
        $q->where('destinationsid', '=', $destinations);
     })->get();
} else {
        echo "No destination provided";
}
Sign up to request clarification or add additional context in comments.

Comments

2

You need to add use() to the closure to pass variables. For example:

->whereHas('destinations', function($q) use($destinations) {

Or, you could just use the request() global helper:

->whereHas('destinations', function($q) {
    $q->where('destinationsid', request('destinations'));

From the docs:

Closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct.

Comments

1

You need to pass destinations variable in your where closure:

$destinations = $request['destinations'];
    if($request->has('destinations'))
    {
        $trips = Trip::where('status','=',1)->whereHas('destinations', function($q) use ($destinations){
        $q->where('destinationsid', '=', $destinations);
        })->get();
    }else{
         echo "No destination provided";
    }

Comments

0

You need to use destinations variable in your where closure:

if($request->has('destinations'))
{

    $destinations = $request['destinations'];
    $trips = Trip::where('status','=',1)->whereHas('destinations', function($q) use ($destinations){
    $q->where('destinationsid', '=', $destinations);
    })->get();

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.