Home > Blockchain >  How to build query for multiple condition for same column in laravel query builder?
How to build query for multiple condition for same column in laravel query builder?

Time:11-24

I want to get count from 'user' table with 'plan_validity' is null or more than today's date. both condition need to check for same column with user_id and status = 1.

  $currentUser = User::where('user_id', $card_details->user_id)
                ->where('status', 1)
                ->where(function (Builder $query) {
                    return $query
                        ->whereDate('plan_validity', '>=', Carbon::now())
                        ->orWhere('plan_validity', null);
                    })->count();

giving error

[2021-11-23 10:40:31] production.ERROR: Argument 1 passed to App\Http\Controllers\ProfileController::App\Http\Controllers\{closure}() must be an instance of App\Http\Controllers\Builder, instance of Illuminate\Database\Eloquent\Builder given, called in /home/hellovcard/public_html/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php on line 237 {"userId":17,"exception":"[object] (TypeError(code: 0): Argument 1 passed to App\\Http\\Controllers\\ProfileController::App\\Http\\Controllers\\{closure}() must be an instance of App\\Http\\Controllers\\Builder, instance of Illuminate\\Database\\Eloquent\\Builder given, called in /home/hellovcard/public_html/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php on line 237 at /home/hellovcard/public_html/app/Http/Controllers/ProfileController.php:34)

how to modify above mentioned query?

this is output I need to get

enter image description here

CodePudding user response:

You are not combining your "where" clauses properly. With the "orWhere" at the end, it essentially ignores all the conditions (ie. which user it relates to) of the preceding where clauses, so adds to the results any row where plan_validity is null. So after you query by user ID and status, you then need to combine the remainder of the query into a logical group like so :

$user = Users::where('user_id', $card_details->user_id)
  ->where('status', 1)
  ->where(function (Builder $query) {
        return $query
            ->whereDate('plan_validity', '>=', Carbon::now())
            ->orWhere('plan_validity', null);
    })
    ->get();
  • Related