phplaravelfilteringlaravel-collection

Laravel collection filter for 'A%' just like we do with where like 'A%'


I want to filter a bunch of names that start with a character followed by wildcard *

Query
I can achieve that with a query e.g. return $q->where('name', 'like', $name . '%');

Since I have the modal::class cached, I don't want to repeat it rather use filter() or something else that can help me get the expected results.

Collection Filter()

return $collection->filter(function ($q) use ($name) {
    return false !== stripos($q['name'], $name); // this returns all the names that contains $name character
});

What I want to achieve is to filter() names that starts with a specific character and then '%' -- $name . '%' e.g. 'A%'

Below are the couple of SO link I went through
Collection Where LIKE Laravel 5.4
Laravel 5.5 Collection where like


Solution

  • You could use the Str::startsWith helper.

    use Illuminate\Support\Str;
    
    $result = Str::startsWith('This is my name', 'This');
    
    // true
    

    Applying to your code, it should be

    use Illuminate\Support\Str;
    
    return $collection->filter(function ($q) use ($name) {
        return Str::startsWith($q['name'], $name);
    });
    

    For laravel versions prior to 5.7, use the starts_with helper instead.

    $result = starts_with('This is my name', 'This');
    
    // true