Laravel Advanced Wheres How to Pass Variable into Function

Laravel Advanced Wheres how to pass variable into function?

You can pass the necessary variables from the parent scope into the closure with the use keyword.

For example:

DB::table('users')->where(function ($query) use ($activated) {
$query->where('activated', '=', $activated);
})->get();

More on that here.

EDIT (2019 update):

PHP 7.4 (will be released at November 28, 2019) introduces a shorter variation of the anonymous functions called arrow functions which makes this a bit less verbose.

An example using PHP 7.4 which is functionally nearly equivalent (see the 3rd bullet point below):

DB::table('users')->where(fn($query) => $query->where('activated', '=', $activated))->get();

Differences compared to the regular syntax:

  • fn keyword instead of function.
  • No need to explicitly list all variables which should be captured from the parent scope - this is now done automatically by-value. See the lack of use keyword in the latter example.
  • Arrow functions always return a value. This also means that it's impossible to use void return type when declaring them.
  • The return keyword must be omitted.
  • Arrow functions must have a single expression which is the return statement. Multi-line functions aren't supported at the moment. You can still chain methods though.

How to pass a variable into an internal function in Laravel 5.3?

There is the use construct that you can use to create a closure around the variable:

->where(function ($query) use($locale) {
$query->where('news.language', $locale)
->orWhere('news.language', 'all');
})

See Example #3 in the manual, "Inheriting variables from the parent scope".

How to pass a function to Having in eloquent?

havingRaw expects just a string parameter and won't work with a closure. You can use the whereHas method like the where method - https://laravel.com/docs/6.x/eloquent-relationships#querying-relationship-existence

Laravel 5 Variable Constructed Query String Eloquent

I'm not 100% sure on exactly what you're asking, but I think the following will work for you.

$batch = MyModel::whereHas('asset', function ($query) use ($settings){
if(isset($settings->new)){
$query->where('created_at','>',Carbon::now()->subMonths(1));
}
if(isset($settings->long)){
$query->where('lengthD','Long');
}
if(isset($settings->short)){
$query->where('lengthD','Short');
}
if(!isset($settings->new)&&!isset($settings->long)&&!isset($settings->short)){
$query->where('id','>',0);
}
})->orderBy('id', 'desc')->take(20)->get();

combining when() and whereBetween() methods in laravel query builder

You can try with this code:

->when($start && $end, function ($query, $condition) use($start, $end) { 
return $query->whereBetween('order_date', [$start, $end]);
})

As already pointed in the comments the tihrd parameter of a when() should be a function, with the use() statement you can pass the variables in the closure.



Related Topics



Leave a reply



Submit