jhoss
jhoss

Reputation: 487

search in collection laravel

I have a very large collection of 150 objects

 ...
 App\almacen {#1679
     id: 124,
     emp_id: 1,
     dst_id: 13,
     hora: 0,
     numMesa: 0,
     event_id: 1,
     created_at: "2018-01-22 11:41:03",
     updated_at: "2018-01-22 11:41:03",
   },
   App\almacen {#1680
     id: 125,
     emp_id: 1,
     dst_id: 11,
     hora: 0,
     numMesa: 0,
     event_id: 1,
     created_at: "2018-01-22 11:41:03",
     updated_at: "2018-01-22 11:41:03",
   },
   App\almacen {#1681
     id: 126,
     emp_id: 1,
     dst_id: 12,
     hora: 0,
     numMesa: 0,
     event_id: 1,
     created_at: "2018-01-22 11:41:03",
     updated_at: "2018-01-22 11:41:03",
   },
   App\almacen {#1682
     id: 127,
     emp_id: 1,
     dst_id: 20,
     hora: 0,
     numMesa: 0,
     event_id: 1,
     created_at: "2018-01-22 11:41:03",
     updated_at: "2018-01-22 11:41:03",
   },
   App\almacen {#1683
     id: 128,
     emp_id: 1,
     dst_id: 7,
     hora: 0,
     numMesa: 0,
     event_id: 1,
     created_at: "2018-01-22 11:41:03",
     updated_at: "2018-01-22 11:41:03",
   },
  ...

and I have to compare if the keys emp_id and dst_id are equal to a number for example 8 and return 'true' if it exists Is there any way to do this without using 'foreach' and looking directly at the object? already use contains (), search () but always return 'false' even if the value does exist

Upvotes: 4

Views: 30525

Answers (4)

Waad Mawlood
Waad Mawlood

Reputation: 888

just use

return $collection->where('price', '100')->toArray();

Upvotes: 0

ahmad-mohammadi
ahmad-mohammadi

Reputation: 187

You can use the where method on collections like this:

$collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
    ['product' => 'Bookcase', 'price' => 150],
    ['product' => 'Door', 'price' => 100],
]);

$filtered = $collection->where('price', 100);

$filtered->all();

Upvotes: 7

Stan Fad
Stan Fad

Reputation: 1234

Laravel 4.2

firstWhere (not working)

first:

$needle = 8;
$exists = $items->first(function($key, $item) use ($needle) { 
      return $item->emp_id === $needle && $item->dst_id === $needle ;
 }) !== null;

filter:

$needle = 8;
$exists = $items->filter(function($key, $item) use ($needle) { 
      return $item->emp_id === $needle && $item->dst_id === $needle ;
 })->count() > 0;

Upvotes: 2

user320487
user320487

Reputation:

Firstwhere:

$exists = $items->firstWhere(['emp_id' => 8, 'dst_id' => 8]) !== null;

First:

$needle = 8;
$exists = $items->first(function($item) use($needle) { 
      return $item->emp_id === $needle && $item->dst_id === $needle ;
 }) !== null;

Filter:

$needle = 8;
$exists = $items->filter(function($item) use($needle) { 
      return $item->emp_id === $needle && $item->dst_id === $needle ;
 })->count() > 0;

Upvotes: 6

Related Questions