Search code examples
laraveldynamiceloquentwith-statementeloquent-relationship

Laravel Eloquent Query WITH parameters


Morning,

il would like to use Eloquent to make this request but i have an error.

$ModelVars=Model1::with(['Model2' => function($query,$var){
                            return $query->where('field1', 'like', '%'.$var.'%');}])->get();

Could somebody help me. Thks in advance.


Solution

  • Change your code to :

    $ModelVars = Model1::with(['Model2' => function($query) use ($var){
        return $query->where('field1', 'like', '%'.$var.'%'); }])
    ->get();
    

    use is not a function, it's part of the Closure syntax It simply makes the specified variables of the outer scope available inside the closure.