تماشای این درس نیاز به اشتراک حرفه‌ای دارد.

Ordering Stores by Distance0:00

In the last lesson, we learned how to limit the Store results to only stores within a 10 kilometer distance. We also updated our schema to use a point geometry column instead of the longitude and latitude columns. In this lesson, we're going to make one more update to this page. We're going to update our query to order the locations by distance so that we can get the closest stores first. Let's go to the StoresController and add a new orderByDistance scope call to this query. And again, we'll pass in the location of the current user to this method. Next, let's add this new scope to the Store model. public function scopeOrderByDistance, and that'll take an instance of the QueryBuilder, our coordinates as well as a direction which will default to ascending. Now, to order the results to the nearest stores, we'll use the orderByRaw method.

Implementing orderByRaw Distance0:36

our coordinates as well as a direction which will default to ascending. Now, to order the results to the nearest stores, we'll use the orderByRaw method and then we'll simply calculate the distance again in the exact same way we did in the previous two lessons using the stdistance function. Then we'll pass in the direction and finally the coordinates as our bindings. However, as we learned in the ordering with nulls always last lesson, we need to be careful to protect ourselves from SQL injection attacks since we can't use a binding for our sort direction. Instead, we'll use a simple validation check. direction equals and we'll get the lowercase version of the direction provided.

Validating Sort Direction1:06

Instead, we'll use a simple validation check. direction equals and we'll get the lowercase version of the direction provided. And if that equals ascending, then we'll use ascending. Otherwise, we'll use descending. Okay, that's it. And if we hit refresh in the browser, we can see that this is working. We're now getting our closest stores listed first. Thank you.

ST_SRID()Query Scopes

دوست دارید گاهی خبرهای Laracasts را ایمیل کنیم؟