Destiny
Destiny

Reputation: 507

How to use a list of IDs in a query

I have a query that filter users to display to admins by ID, now I would like to expand this query to accommodate more IDs like 2,3,4,5 and 6, so how do I arrange it in a list

public function vipusers()
{
    $data['title'] = 'Vip Users';
    $is_super = !auth()->guard('admin')->user()->is_super;

    $data['users'] = Users::when($is_super, function ($q) {
        $q->where('id', '!=', 1);
    })
        ->orderBy('id', 'DESC')->get();

    return view('admin.dashboard.manage', $data);
}

Upvotes: 1

Views: 142

Answers (3)

Destiny
Destiny

Reputation: 507

This solved what I'm trying to achieve according to https://laravel.com/docs/8.x/queries#where-clauses

public function vipusers()
{
    $data['title'] = 'Vip Users';
    $is_super = !auth()->guard('admin')->user()->is_super;

    $data['users'] = Users::when($is_super, function ($q) {
        $q->where('id', '!=', 1)
          ->where('id', '!=', 2)
          ->where('id', '!=', 3);
    })
        ->orderBy('id', 'DESC')->get();

    return view('admin.dashboard.manage', $data);
}

Upvotes: 0

Hassaan Ali
Hassaan Ali

Reputation: 1061

Extending @Bazaim's answer.

Consider using a function to iterate through all the users, by passing the id from table to the function. Consider using the following snippet.

public function vipusers($id)
{
    $data['title'] = 'Vip Users';
    $is_super = !auth()->guard('admin')->user()->is_super;

    $data['users'] = Users::when($is_super, function ($q) {
        $q->where('id', '!=', $id);
    })->orderBy('id', 'DESC')->get();

    return view('admin.dashboard.manage', $data);
}

Upvotes: 0

Obzi
Obzi

Reputation: 2390

You can use whereIn :
https://laravel.com/docs/8.x/queries#additional-where-clauses

$ids = [2, 3, 4, 5, 6];
$users = Users::whereIn('id', $ids)->orderBy('id', 'DESC')->get();
...

Upvotes: 2

Related Questions