Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rijad1802's avatar

Toggle between ASC and DESC ordering

Hello everyone,

I'm new in Laravel and I'm stuck while trying to order some data by column. So, I have this situation:

-I've made button inside form:

form method="GET" action="/sortByMovies"> button class="btn btn-default" type="submit"> /form>

-Also, I've route:

Route::get('/sortByMovies', 'MovieController@sortByMovies');

-And, finally, function looks like:

    $movies = Movie::orderBy('movie_name')->get();
            return view('movies.index', compact('movies'));

-And, this works fine, but when I click on the button again, I want to order in descending way, ie. I want this button to toggle between asc and desc. I tried a lot of things, but unsuccessfully.

0 likes
5 replies
Cronix's avatar

If you want to alternate when clicking the same button, you'd need to store it in session or something, so that when they click it you read from session in the controller to see what it was last. If it was "desc", then sort by "asc" and set it in session. Next time it's clicked, read from session again. If it's "asc" sort by "desc" and set it in session, etc.

https://laravel.com/docs/5.6/session#using-the-session

1 like
Cronix's avatar
// read from session, use 'desc' if not set
$sortOrder = $request->session()->get('sortOrder', 'desc');

// do the query
$movies = Movie::orderBy('movie_name', $sortOrder)->get();

//toggle the sort order for next time
$sortOrder = $sortOrder == 'desc' ? 'asc': 'desc'

// store in session for next time
$request->session()->put('sortOrder', $sortOrder);
2 likes
rijad1802's avatar

this is confusing for me, I need to learn more to get this things clear. :(

Thank you for your help, I appreciate it.

Cronix's avatar

Which part is confusing? The session? Or storing/retrieving data from session?

Snapey's avatar

you dont need to store in session. that is one approach.

Another is to sort one way by default and the other way with a querystring

So suppose your route is /movies This can have a default sort order like;

$sort = request('sort','asc');

$movies = Movie::orderBy('movie_name',$sort)->get();
return view('movies.index', compact('movies','sort'));

if you add ?sort=desc to the url then this will be passed through to your orderBy otherwise asc is used

You will notice I passed $sort to the view. This is so you can decide which link to use and how to display the button

Please or to participate in this conversation.