Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel where with if else

In my Laravel project I'm building a query with some conditionals. There is one issue that I can't get my head around

I have a Query that goes as follows

$query = SocialMediaFeed::where('location_id', $location_id);

Now there are some feed items which have 'self' = true.. These should be ignored from the results at first, unless when there is a $filters array.

if(!$filters) {
    $query = $query->where('self', '<>', true);
}

Now I'm wondering, If there are filters, it should include the data that I got when self not equal to true, but also the data if it is true..

I tried the following, But that only returns the self=true posts, instead of all posts combined with self=true

$query = $query
    ->where('self', '<>', true)
    ->where('self', true)
    ->orWhereNull('self');
like image 611
Miguel Stevens Avatar asked Jun 01 '26 20:06

Miguel Stevens


1 Answers

You can use Conditional Clauses for this:

// false: All social media feeds except where self is not true
// true: All social media feeds
$filters = false;
$query = SocialMediaFeed::where('location_id', $location_id)
->when(!$filters, function ($query) {
    return $query->where('self', '!=', true);
})->get();
like image 87
Björn Avatar answered Jun 03 '26 10:06

Björn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!