Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display records in view based on their first letter?

In my controller I am passing to a view a bunch of categories in alphabetical order like this :

public function index()
    {
        $categories = Category::orderBy('name', 'asc')->get();

        return view('categories')->with('categories',$categories);
    }

In my view, I want to display in separate columns corresponding to letters from the alphabet each of these categories, so in column "A" I will have all categories starting with A and so on.

Is it possible to filter the results in the view by letter in order to achieve this, and if yes, how can it be done?

like image 586
incense_stick Avatar asked Jan 29 '23 23:01

incense_stick


1 Answers

You can group the list of categories by first letter in your controller and then pass the result to your view, here is how to do:

Controller:

public function index() {

    $categories = Category::orderBy('name', 'asc')->get();

    $groups = $categories->reduce(function ($carry, $category) {

        // get first letter
        $first_letter = $category['name'][0];

        if ( !isset($carry[$first_letter]) ) {
            $carry[$first_letter] = [];
        }

        $carry[$first_letter][] = $category;

        return $carry;

    }, []);

    return view('categories')->with('groups', $groups);
}

View:

@foreach($groups as $letter => $group)

    <ul>

        <li>{{ $letter }}</li>

        @foreach($group as $category)

            <li>{{ $category['name'] }}</li>

        @endforeach

    </ul>

@endforeach

Here is a working example using array_reduce (it's the same as Collection::reduce function above)

like image 54
YouneL Avatar answered Feb 05 '23 16:02

YouneL