Laravel Eloquent with non identifying variables

I am trying to use laravel-eloquent to get rooms and their reservations that are after a certain date.

$fdate='2015-01-05';
$roomdata=Rooms::where('city_id','=',$citydata['id'])
->with('types')
->with('localities')
->with('slideshow')
->with(array('booking' => function($query){
    $query->where('bookstart','>',$fdate);
}))
->get();

      

This is giving me an error saying there $fdate

is undefined. But when I do

$query->where('bookstart','>','2015-01-05');

      

This works great. Any reason for this? Can someone provide a good solution to this problem?

+3


source to share


3 answers


You are using a closure inside a callback before with

. First, a quote from this page of the doc:

A closure can also inherit variables from the parent scope. Any such variables must be passed to the construct of the language of use.

You are trying to access a variable from the parent scope inside your anonymous function, so you first need to pass it to the construct use

so that PHP knows that you are creating a closure around that variable:

$roomdata = Rooms::where('city_id','=',$citydata['id'])
    ->with('types')
    ->with('localities')
    ->with('slideshow')
    ->with(array('booking' => function($query) use($fdate) {
        $query->where('bookstart','>',$fdate);
    }))
;

      



Contrast this with Javascript, which allows the programmer to automatically access the parent scope, since each child scope is part of the parent scope of the Scope Chain . Something like this would be valid in Javascript:

var foo = 'bar';
(function() {
    alert(foo);
})();

      

In PHP, accessing external variables from internal functions is not automatic. Thus, PHP distinguishes between closures and anonymous functions (aka 'lambdas') in such a way that JavaScript has at least no syntax. However, this is not explicitly stated in the documentation (the manual seems to equate the two when they don't really match).

+4


source


Variable scope:



    $fdate='2015-01-05';
    $roomdata=Rooms::where('city_id','=',$citydata['id'])
    ->with('types')
    ->with('localities')
    ->with('slideshow')
    ->with(array('booking' => function($query) use ($fdate){
        $query->where('bookstart','>',$fdate);
    }))
    ->get();

      

+1


source


put a semicolon like so:

$fdate='2015-01-05';

      

0


source







All Articles