user10139010
user10139010

Reputation:

Laravel query for hiding records on a boolean

I am trying to write a query which lists all the products where purchased = true. If a product has the field includes_bonus set to true it should then hide the bonus product which has the id of 2 on the blade.

use case:

if includes_bonus is set to 1 on any of the product records always hide product with id of 2. If includes_bonus is 0 on all records always display product with id of 2.

Current Query

Below is the query i have created, the problem is when you turn off a product with includes_bonus set to true and then turn on the product with the id of 2 individually it hides that record.

$purchasedProducts = $user->products()->where('purchased', 1);
        if ($user->products()->where('includes_bonus', '=', 1)->first()) {
            $purchasedProducts->where('products.id', '!=', 2);
        }
        $purchasedProducts = $purchasedProducts->get();

blade foreach

I then plan to loop through each record and display it on the page

 @foreach($purchasedProducts as $purchasedProduct)

How do i modify this query to ensure the product id of 2 is always hidden when includes_bonus is true and when its false always show?

Upvotes: 0

Views: 568

Answers (1)

lagbox
lagbox

Reputation: 50491

You could get all the records then see if they contain this particular condition, if so then get the Collection without the id 2:

$purchasedProducts = $user->products()->where('purchased', 1)->get();

if ($purchasedProducts->contains('includes_bonus', 1)) {
    $purchasedProducts = $purchasedProducts->except(2);
}

Laravel 8.x Docs - Collections - Available Methods - contains

Laravel 8.x Docs - Eloquent Collections - Available Methods - except

Upvotes: 1

Related Questions