Laravel - Collections - Method Sole

The sole method returns the first element in the collection that passes a given truth test, but only if the truth test matches exactly one element:

    
    collect([1, 2, 3, 4])->sole(function ($value, $key) {
        return $value === 2;
    });
    
    // 2
	

You may also pass a key / value pair to the sole method, which will return the first element in the collection that matches the given pair, but only if it exactly one element matches:

    
    $collection = collect([
        ['product' => 'Desk', 'price' => 200],
        ['product' => 'Chair', 'price' => 100],
    ]);
    
    $collection->sole('product', 'Chair');
    
    // ['product' => 'Chair', 'price' => 100]
	

Alternatively, you may also call the sole method with no argument to get the first element in the collection if there is only one element:

    
    $collection = collect([
        ['product' => 'Desk', 'price' => 200],
    ]);
    
    $collection->sole();
    
    // ['product' => 'Desk', 'price' => 200]
	

If there are no elements in the collection that should be returned by the sole method, an \Illuminate\Collections\ItemNotFoundException exception will be thrown. If there is more than one element that should be returned, an \Illuminate\Collections\MultipleItemsFoundException will be thrown.