tonics
tonics

Reputation: 35

Laravel Eager Load with dynamic constraints

Can anybody please help me to understand why the following code is working

$x = $widget->objGallery->galleryItems()->with(array('captions' => function($query){ $query->where('locale', 'IT' );}))->get() ;

but when I am using a dynamic value

$id='11';
$x = $widget->objGallery->galleryItems()->with(array('captions' => function($query){ $query->where('locale', $id );}))->get() ;

is saying

Method Illuminate\View\View::__toString() must not throw an exception

Upvotes: 1

Views: 3234

Answers (2)

fractefactos
fractefactos

Reputation: 377

You can't, if you want to query by a relationship you need to use whereHas.

This is, for the conception of eager loading, just clarify... With syntax fix on @Marcin Nabiałek's response, that where in the "with" function works only on the eager loading data, not in the main query.

Upvotes: 0

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111899

In fact it's hard to say because you haven't showed here relevant code, but the problem with code:

$x = $widget->objGallery->galleryItems()->with(array('captions' => 
      function($query){ $query->where('locale', $id );
     }))->get();

is that variable $id is undefined here. You need to add use to use if in closure, so the code should look like this:

$x = $widget->objGallery->galleryItems()->with(array('captions' => 
      function($query) use($id) { $query->where('locale', $id );
     }))->get();

You should change your environment to local and have turned on debugging, probably you would then know about this problem. Probably when correcting this code as I showed you won't have the error.

Upvotes: 12

Related Questions