Home > OS >  Collection query
Collection query

Time:06-15

I have a collection which contains these values

'sales marketing|telemarketing', 

what I'm trying to do is query/filter the items in collection but just based on the individual type so the for example value of 'telemarketing'. I have tried

$results = $data->where('Department', 'contains', $type); and also tried LIKE but because of the format with the pipe it's not picking the type/value.

This might be a dumb question but any ideas would be great!

CodePudding user response:

The where-method also can handle only two Parameters. For example:

$data= collect([
  ['Department' => 'sales', 'price' => 200],
  ['Department' => 'marketing', 'price' => 100],
  ['Department' => 'telemarketing', 'price' => 150],
  ['Department' => 'marketing', 'price' => 100],
]);

$departmentName = "marketing"; 

$results = $data->where('Department', $departmentName);

dd($results);

CodePudding user response:

Given your example:

[
  "Employee" => "Some Company",
  "Name" => "John Something",
  "Usages" => "sales marketing|telemarketing",
  "StartDate" => "1st Mar 2021",
  "EndDate" => ""
]

The main issue is that the "Usage" property is a string containing multiple values, with the pipe character acting as a separator. One solution to filter by one of those values is by mapping your original collection to transform the string in an array with the explode method and then use the filter method to filter based on the Usages you're interested in. The resulting code might look like this:

$mappedCollection = $collection->map(function($el) {
    $el['Usages'] = explode('|', $el['Usages']); // Transform the string into an array
    return $el;
});

$result = $mappedCollection->filter(function($el) {
    return in_array('sales marketing',$el['Usages']); // Change 'sales marketing' with the desired Usage
});
  • Related