Home > Database > Mysql Tutorial > How Can I Pass Variables into Laravel Advanced Where Closures?

How Can I Pass Variables into Laravel Advanced Where Closures?

Susan Sarandon
Release: 2024-12-24 20:34:10
Original
710 people have browsed it

How Can I Pass Variables into Laravel Advanced Where Closures?

Passing Variables into Laravel Advanced Where Closures

The Laravel documentation provides an example of using whereExists with a closure to join tables:

DB::table('users')
    ->whereExists(function($query)
    {
        $query->select(DB::raw(1))
              ->from('orders')
              ->whereRaw('orders.user_id = users.id');
    })
    ->get();
Copy after login

But what if you need to pass an external variable into the closure, such as a search query?

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

})
Copy after login

The current solution is to create a new property and access it using $this, but is there a more convenient way?

Yes, you can use the use keyword to pass variables from the parent scope into the closure:

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

In PHP 7.4, you can use the shorter arrow function syntax:

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

Key differences between arrow functions and regular closures:

  • fn keyword instead of function
  • Variables are automatically captured from the parent scope
  • Arrow functions always return a value
  • Return keyword must be omitted
  • Arrow functions must have a single expression as the return statement

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template