Laravel Advanced Wheres how to pass variable into function?
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
:
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:
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:
Conditional constraints application
Laravel also capacitates querying in a more expressive language using when
to put variable-based conditional constraints:
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:
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.
Was this article helpful?