Laravel Advanced Wheres how to pass variable into function?

前端 未结 4 2018
面向向阳花
面向向阳花 2020-11-29 18:38

Example in doc:

DB::table(\'users\')
        ->whereExists(function($query)
        {
            $query->select(DB::raw(1))
                  ->fro         


        
相关标签:
4条回答
  • 2020-11-29 18:53

    You can pass variables using this...

    $status =1;
     $info = JOBS::where(function($query) use ($status){        
             $query->where('status',$status);
             })->get();
    print_r($info);
    
    0 讨论(0)
  • 2020-11-29 18:56

    @kajetons' answer is fully functional.

    You can also pass multiple variables by passing them like: use($var1, $var2)

    DB::table('users')->where(function ($query) use ($activated,$var2) {
        $query->where('activated', '=', $activated);
        $query->where('var2', '>', $var2);
    })->get();
    
    0 讨论(0)
  • 2020-11-29 18:56

    If you are using Laravel eloquent you may try this as well.

    $result = self::select('*')
                        ->with('user')
                        ->where('subscriptionPlan', function($query) use($activated){
                            $query->where('activated', '=', $roleId);
                        })
                        ->get();
    
    0 讨论(0)
  • 2020-11-29 19:12

    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.
    0 讨论(0)
提交回复
热议问题