Method 1: Laravel Basic Query Multiple WHERE Condition
To basic way to query with multiple where clauses are to chain the "where" method continuously and passing in the condition as follows.
<?php $results = Post::query() ->where('post_status', '=', 1) ->where('user_id', '=', 1) ->where('published_code', '=', 1) ->get();
Method 2: Laravel Query Multiple WHERE Condition With Array
Another approach is to pass in an associative array that contains the different types of conditions.
<?php $results = Post::query() ->where([ ['post_status', '=', 1], ['user_id', '<>', 1] ]) ->get();
<?php $users = DB::table('users') ->whereColumn([ ['first_name', '=', 'last_name'], ['updated_at', '>', 'created_at'] ])->get();
Method 3: Multiple WHERE Condition with Model Scopes
The next method is to define your condition from within the Model class itself, this way you will be able to have a more expressive and elegant syntax.
<?php // app/Models/Post.php class Post extends Model { public function scopeActivePost($query) { return $query ->where('post_status', '=', 1) ->where('user_id', '=', 1); } public function scopeMainUser($query) { return $query ->where('post_status', '=', 1) ->where('user_id', '=', 1); } }
<?php Post::activePost()->mainUser()->get();
Method 4: Laravel Multiple WHERE Condition With Sub Query
The next method is to use a sub-query to define the WHERE condition and it will like below.
<?php Post::query() ->where('post_status', '=', 1) ->whereNotNull('created_at') ->whereNotNull('updated_at') ->where(function($query){ return $query ->whereNotNull('user_id') ->where('your_condition_here', '=', 'your_value_here'); });
Leave a reply