Explain Codes LogoExplain Codes Logo

Laravel Advanced Wheres how to pass variable into function?

php
closure
variable-scope
php-74
Alex KataevbyAlex KataevยทSep 6, 2024
โšกTLDR

In Laravel, external variables can be injected into a closure via the use keyword. By utilizing this feature in where queries, your query's conditions can become dynamic and flexible. Here's a snapshot of this in action with the variable $age:

$age = 25; //Just a random age, not my actual age! ๐Ÿ˜‰ $users = User::where(function($query) use ($age) { //Fetching those who can rent a car without an underage fee! $query->where('age', '>', $age); })->get();

Now if you're using PHP 7.4 or higher, you can switch to arrow functions for a more elegant look and to skip writing the use keyword as shown here:

$age = 25; // Life begins at 25 right? ๐Ÿ˜‰ $users = User::where(fn($query) => $query->where('age', '>', $age))->get();

This fn is short, sweet, and equally powerful!

Advanced Where & Variable Scope Management

Handling multiple variables

When dealing with a scenario of passing multiple external variables in the closure, you can pass them inside the use statement like so:

$minAge = 18; // It's legal ๐ŸŽ‰ $maxAge = 35; // Sweet spot? ๐Ÿ˜‰ $users = User::where(function($query) use ($minAge, $maxAge) { // Only interested in prime time individuals! $query->whereBetween('age', [$minAge, $maxAge]); })->get();

Conditional constraints application

Laravel also capacitates querying in a more expressive language using when to put variable-based conditional constraints:

$age = 25; // Is 25 the new 18? $occupation = 'developer'; // Who wouldn't love smart people? $users = User::when($age, function($query) use ($age) { return $query->where('age', '>', $age); })->when($occupation, function($query) use ($occupation) { return $query->where('occupation', $occupation); })->get();

when lends a helping hand by performing truth tests to decide if the closure should run.

PHP7.4 Arrow functions: Leveraging concise syntax

Caught by the Arrow!

Arrow functions, introduced in PHP 7.4, brought a short yet sufficiently powerful syntax variant of anonymous functions that TBH makes coding a lot cooler. They leverage you to cut down boilerplate code, making things tidier. Oh, and they also capture variables automatically, so say goodbye to manually specifying use.

Gotchas with Arrow functions

While the arrow functions do hit the bullseye with their concise syntax, remember they have a caveat. They allow operating on a single-line expression only, so multiline statements are a no-go. It's the trade-off for conciseness, so use 'em judiciously.

Nested closures & variables

Handling nested closures will often need variables to be passed down multiple levels:

$limit = 100; // Because 100 is a cool number! ๐Ÿ˜Ž $users = User::where(function($query) use ($limit) { $query->where('score', '>', 50) ->orWhere(function($subQuery) use ($limit) { // Here we pull a stunt by using limit in multiple levels $subQuery->where('views', '>', $limit); }); })->get();

Scope and shadowing considerations

Shadowing can be a party pooper in the whole closures business. To avoid unexpected behaviors due to variable shadowing, always give distinctive names to parameters in your closure that do not coincide with your external variables.