Home >Database >Mysql Tutorial >How Can I Pass Variables to Laravel's Advanced Where Closures?

How Can I Pass Variables to Laravel's Advanced Where Closures?

Linda Hamilton
Linda HamiltonOriginal
2024-12-20 22:04:12164browse

How Can I Pass Variables to Laravel's Advanced Where Closures?

Passing Variables into Laravel's Advanced Where Closures

Laravel's advanced where functions provide powerful ways to filter your queries. However, you may encounter situations where you need to pass external variables into the closure used in the where function.

Example Scenario

Suppose you want to use an external variable, such as $searchQuery, in your where closure:

->where('city_id', '=', $this->city->id)
->where(function($query)
    {
        $query->where('name', 'LIKE', '%'.$searchQuery.'%')
        ->orWhere('address', 'LIKE', '%'.$searchQuery.'%')

    })

Use Keyword Solution

You can pass the necessary variables into the closure using the use keyword:

DB::table('users')->where(function ($query) use ($searchQuery) {
    $query->where('name', 'LIKE', '%'.$searchQuery.'%')
    ->orWhere('address', 'LIKE', '%'.$searchQuery.'%')
})->get();

PHP 7.4 Arrow Function (Update)

In PHP 7.4 and later, you can use arrow functions for a more concise syntax:

DB::table('users')->where(fn($query) => $query->where('name', 'LIKE', '%'.$searchQuery.'%')
->orWhere('address', 'LIKE', '%'.$searchQuery.'%'))->get();

Unlike regular anonymous functions, arrow functions automatically capture variables from the parent scope and do not allow explicit listing via use. However, they must have a single return statement and cannot contain multiple lines of code.

The above is the detailed content of How Can I Pass Variables to Laravel's Advanced Where Closures?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn