ahmeda's avatar

how to block user by store in Laravel

I have an e-commerce app using Laravel multi-stores I have a feature that stores can block specific user

the structure of DB:

stores table:
id - name - etc  ...

users table:
id - name - etc  ...

products table:
id - name - store_id - etc ...

blocked_users table: "this table contains users that store blocked" 
id - user_id - store_id - created_at - updated_at

I need when a store block a user the products of this store does not show to this blocked user

my query:

 $products = Product::query()
            ->with(['store.blocked' => function ($q) {
                $q->where('user_id', '!=', auth()->id());
            }])
            ->whereHas('store.blocked', function ($q) {
                $q->where('user_id', '!=', auth()->id());
            })
            ->take(12)
            ->get();

With this query, I got no products at all!

Blocked is a relation in the Store model:

public function blocked()
{
  return $this->hasMany(BlockedUsers::class);
  // BlockedUsers model of "blocked_users" table
}
0 likes
5 replies
ahmeda's avatar

@Tray2 I knew this but my query to API and I want to show other products to a user and hide the products of that store!

Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

My guess is that you have to reverse it

$products = Product::query()
            ->with(['store.blocked' => function ($q) {
                $q->where('user_id', '!=', auth()->id());
            }])
            ->whereDoesntHave('store.blocked', function ($q) {
                $q->where('user_id', '=', auth()->id());
            })
            ->take(12)
            ->get();
ahmeda's avatar

@Sinnbeck That is the right one! thank you so much

can you pls explain why u put '!=' with "with" and whereDoesntHave !

Sinnbeck's avatar

@Jean_ali well with you can remove I think. I don't see any need for knowing what other users are blocked on a product/store

Regarding whereDoesntHave, you just need to understand whereHas. Imagine you call the stores manually to know if you have a certain user blocked. You ask "do you have any users blocked who isn't him?". One store doesn't have anyone blocked, and therefor says "no we don't have anyone blocked who isn't him". You take that to mean that he is blocked.

whereHas = has 1 or more items that fulfill the check

whereDoesntHave = has 0 items fullfil the check (is this person on your list)

1 like

Please or to participate in this conversation.