Search code examples
laraveleloquentlaravel-collection

Laravel Collection Where Index


i have this collection below

[
   {
      "id":"6ad91b63-d964-4155-b16a-47fc246b6aa3",
      "content":"",
      "to":[
         "6ea94472-7db6-4d66-a485-30f99d46d039",
         "37c61b0b-2b75-4652-9ee9-b8d54fde3fe9",
         "335e9ee7-02ff-494d-89e9-b69b76d0504b",
         "7f67f3aa-7fdf-461c-aaf9-90293067363f",
         "a30477c8-256c-4ba8-aa69-22d7190516dd"
      ],
      "type":"berita",
      "created_by":"363b75f2-8f01-422d-a3cb-ea501d9b5edd",
      "created_at":"2022-01-12T18:22:51.000000Z",
      "updated_at":"2022-01-12T18:23:47.000000Z"
   }
]

and i would like to find by columns "to" where "to" is value that i define. I was trying to use where collection but still get nothing. Here's my eloquent calls

$feed = Feed::latest()
             ->get()
             ->where('to','a30477c8-256c-4ba8-aa69-22d7190516dd');

Solution

  • You could use filter directly (which where uses):

    $collection->filter(fn ($item) => in_array('a30477c8-256c-4ba8-aa69-22d7190516dd', $item->to))
    

    Laravel 8.x Docs - Collections - Available Methods - filter

    PHP.net Manual - Function Reference - Arrays - Array Functions - in_array