tomasosho's avatar

How to create A-Z pagination

In laravel How can I create A-Z pagination for example I've a table users

I want to create sorting pagination from the first letter like In character A all the users starting with A must be the same with A-Z.

0 likes
4 replies
jlrdw's avatar

Use orderBY in the query, the paginator is just for the links.

newbie360's avatar

i don't know if this is what you mean

route:

Route::get('/users/{char?}', 'UserController@index')
    ->where('char', '[A-Z]')->name('users.index');

controller:

public function index($char = '')
{
    $users = User::when($char, function ($query) use ($char) {
        // make sure `name` field is added index
        return $query->where('name', 'like', "{$char}%");
    })
    ->paginate(20);

    return view('index', compact('users', 'char'));
}

view:

@foreach (range('A', 'Z') as $value)
    @if ($char == $value)
        {{ $value }}
    @else
        <a href="{{ route('users.index', $value) }}">{{ $value }}</a>
    @endif
@endforeach
1 like
tomasosho's avatar

Thanks this makes sense! I just have to figure out how to include my query but thank you!.

hanif-king's avatar

you question is not more specific to clarify what you want. but as what i got from your writing. if you want to have a pagination ascending or descending its done in your query like specifying orderBy and its flow like this Users::all()->orderBy('your_column_name_which_you_want_to_filter_based_on_it', 'asc')->paginate(10)

Please or to participate in this conversation.