user7345776
user7345776

Reputation:

Retrieving items Based on multiple IDS in Laravel

I have a relationship between employees and items. It's a one-to-many relationship (i.e employee can have many items).

For instance, there are two employees Mark and Bill.

Mark bought items with item_no 1-0234, 1-0235 respectively.

Bill bought items with item_no 1-0236, 1-0237 respectively.

Item numbers are unique and therefore can be used to find the customer who is in possession.

This is my code to find customers items belong to. I select ids of all items using a checkbox.

What I am looking to achieve is, I want to find all employees based on the item selected, retrieve the phone numbers and item_nos using explode and process a message to them.

Controller

<?php

public function processMessage(Request $request)
{
    $ids = $request->ids; // i am able to get the item_nos selected, eg. 1 - 0234, 1 - 0236

        $split = explode(",", $ids);
        if (request()->ajax()) {
            $employees = Employee::whereHas('items', function ($emp) use ($split) {
                $emp->where('id', $split);
            })->get();

            $get_name = [];
            $get_phone = [];

            foreach ($emps as $key => $emps) {
                $get_name[] = $emps->name;
                $get_phone [] = $emps->phone;
            }

        }

     return ['success' => $get_phone];
}

PS: in the code, imagine i have selected two items with item_nos 1-0234, 1-0236. That is, my code should return two phone numbers, i.e for Mark and Bill but it returns just one of them, which is Mark's. Why is this happening

Upvotes: 0

Views: 470

Answers (1)

Sohel0415
Sohel0415

Reputation: 9853

If i correct, following should help inside your query function-

$emp->whereIn('id',$split);

Upvotes: 1

Related Questions