Search code examples
arrayslaravelcollectionscontains

Laravel - Check if value is present in array


Why does this code return false every time?

$lics = collect(['lic100' => auth()->user()->lic100, 'lic250' => auth()->user()->lic250, 'lic500' => auth()->user()->lic500]);
$licsowned = $lics->filter()->keys();
$haslicense = property_exists($licsowned, $data['lictype']);

$licsowned:

Illuminate\Support\Collection {#367 ▼
 #items: array:3 [▼
  0 => "lic100"
  1 => "lic250"
  2 => "lic500"
 ]
}

$data['lictype'] has the value lic250

I also tried with in_array() but it gave the error message that the value must be an array and I passed an object.


Solution

  • You need to use contains() method of Collection instance.

    For example:

    $collection = collect(['name' => 'Desk', 'price' => 100]);
    
    $collection->contains('Desk');
    

    Or, in your task:

    $lics = collect(['lic100' => auth()->user()->lic100, 'lic250' => auth()->user()->lic250, 'lic500' => auth()->user()->lic500]);
    
    $lics->contains('lic250');
    

    More info:

    https://laravel.com/docs/7.x/collections#method-contains