ssuhat
ssuhat

Reputation: 7656

Check if the user_id is exist inside query

I've tried to query using laravel eloquent where user is following a specific brand.

The problem: How to query listing of brand and let me know if current login user is following the brand?

got 3 tables:

Brand:

Id | name | logo

User:

Id | name | email | password

Followers:

brand_id | user_id

Now i tried to query all brand and inside of the collection i want to add

 is_follow = 1 or is_follow = 0 

if the user already follow or 0 if not exists.

I'm using fractal so maybe it can be easier to query. but i don't really get it how to query it out with check the user_id first.

Thanks

*Update

I manage to solve it. But i think its a bad practice.

  $user_id = Request::get('user_id');

  foreach($brands->followers as $value){
        $array[] = $value->user_id;
    }

    if(in_array($user_id, $array)){
        $is_follow = 1;
    }

Upvotes: 0

Views: 67

Answers (1)

Adrenaxus
Adrenaxus

Reputation: 1613

You can check if the authenticated User follows a specific Brand with:

$user = Auth::user();
$exists = $user->brands->contains($brand_id);

You can also do it with a raw query which will be better in terms of performance:

$exists = DB::table('user_brand')
    ->whereBrandId($brand_id)
    ->whereUserId(Auth::user()->id)
    ->count() > 0;

Upvotes: 1

Related Questions