Home > Net >  Execute Query after value from Multiselect in Laravel
Execute Query after value from Multiselect in Laravel

Time:09-16

Hi I am working in Laravel.

I need to select all rows from databse with selected company_id. In form company_id is multi select

This is what I have done

$data = $request->All();
$notifyTo = $data['notify_to']; /**value from multiselect which is an array**/
foreach($notifyTo as $noTo => $value){
$user = User::all()->where('company_id', "=", $value)->where('status', "=", 1); 
            }
            print_r($user); exit;

here $data['notify_to'] is the value from multiselct , which is an array of company_id Array ( [0] => 11 [1] => 22 [2] => 33 )

Table Structure

| id | name | company_id | status |
-----------------------------------

CodePudding user response:

You can use

User::whereIn('company_id', $data['notify_to'])->where('status', 1)->get();

It will solve your issue.

If you have multiple filters and you want to add multiple "if conditions" if filters are set properly then use the following code structure.

$query = User::where('status', 1);

if (isset(filters['filtername']) {
  $query->where(filters['filtername']);
}

multiple filter conditions.
...
... 

$userObject = $query->get;

It will give you a collection of users based on applied filters.

CodePudding user response:

Use whereIn() clause

$data = $request->All();
$notifyTo = $data['notify_to'];
$user =  User::whereIn('company_id', $notifyTo)->whereStatus(1)->get();
print_r($user);

Make sure $notifyTo is an index array. If not use array_values()

  • Related