alpha's avatar

How to orderBy data?

Hello, I am having trouble ordering numbers in laravel

Minecraft::where('slug', $slug)->firstOrFail()->episodes()->orderBy('episode', 'desc')->get();;

This is my code, It did well to order the episode from 9 to 1 (desc) but when it reach 10 it start at the part after 1

9, 8, 7, 6, 5, 4, 3, 2, 12, 11, 10, 1

what do i need to get the value from higher to lower?

12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1

thank you

0 likes
8 replies
lindstrom's avatar

Is episode an integer or a string? How did you define it in your migration? It looks like it is ordering it as a string.

bobbybouwmann's avatar

Do you save the values as strings? In that case the value would be ordered like your example at the top. You need to make sure the value in your database is of the type integer.

1 like
alpha's avatar

@bobbybouwmann if it's an integer, would it be in order?.. but aren't there any way to order this as a string?.. because almost all the query in the application use this... I have to change all than.

alpha's avatar

@bobbybouwmann thank you ;) solve it already. I order it by created_at By the way thanks everyone!! <3

@bobbybouwmann oh ya... How can I redirect all the NotFoundHttpException to the home page? or when someone went to the wrong route I will display the web page is not available with my own customization.. thank you

jteasyhf's avatar

Hello! It seems like you're encountering a common issue when ordering numbers in Laravel, particularly when dealing with episode numbers. The problem you're facing is related to string sorting rather than numerical sorting, and it's causing the order to be incorrect when numbers have different lengths.

To resolve this, you can modify your query to cast the 'episode' column as an integer before ordering. Here's an updated version of your code:

Now, let's relate this solution to the anchor "Play Minecraft with friends." Just like how collaborating with friends in Minecraft enhances the gaming experience, optimizing your code with the correct sorting approach enhances the functionality and user experience of your application. It ensures that your episodes are presented in the right order, allowing users to navigate through the content seamlessly, much like playing Minecraft with friends creates a more enjoyable and cohesive gaming environment. By addressing this sorting issue, you're enhancing the overall experience for users interacting with your Minecraft-related content..... Visit: (minecraftofficial.com/minecraft-pe-apk/)

Please or to participate in this conversation.