mercredi 3 février 2016

How do I pass through a variable with my filter() for Laravel Collections

I have a simple collection that I want to filter. Take the following example:

// Create an array of fruits
$array = ["banana", "apple", "orange"];

// Transform the array into a Collection object
$collection = new Illuminate\Support\Collection($array);

// We don't like banana's anymore, so we're going to filter them out
$no_bananas = $collection->filter(function($element) {
    if ($element != "banana") return true;
});

// Dump out our array now, and we'll see the banana's are gone
dd($no_bananas);

Works great assuming I only ever want to filter by 'banana'. What if I want to use a variable within the filter. How do I do that?

// Create an array of fruits
$array = ["banana", "apple", "orange"];
$filterby = 'apple';

// Transform the array into a Collection object
$collection = new Illuminate\Support\Collection($array);

// We don't like banana's anymore, so we're going to filter them out
$filtered = $collection->filter(function($element) {
    if ($element != $filterby) return true;
});

// Dump out our array now, and we'll see the banana's are gone
dd($filtered);

The above won't work because $filterbyisn't available in the filter() function. How would I make it available?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire