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?

Anon
  • 523
  • 1
  • 7
  • 25

4 Answers4

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";
}
Hiren Gohel
  • 4,942
  • 6
  • 29
  • 48
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.

Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
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";
    }
Sohel0415
  • 9,523
  • 21
  • 30
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();
Boghani Chirag
  • 217
  • 1
  • 8