[04/10] Laravel Travel API: Tours Filtering and Ordering

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this case we will kind of finish the last lesson of endpoint of Tours by travel and we will add filtering and ordering as the client described in this description currently our controller looks like this so we're just querying all the tours ordering by starting date as the client suggested and then in here we need to add more conditions so if the request contains filtering by date from or date 2 price from or Price 2 and also order by Price ascending or descending which should be in the parameters so our goal is to have requests something like this so this is where I kind of show Almost the final result but these are the parameters so date from day two price from Price 2 sort by and sort order so these would be optional potential parameter that we need to handle and are of course as always a few ways to do that of course you can do Travel Tours and what I often see people doing Do query like this than if request which is a global helper for example date from then query where something and then at the end the actual tours would be equal query then order by something like this so basically you have a lot of if statements but in eloquent there's a more convenient way to write that without the if statements which is one condition so we get back to tours equals Travel Tours order by and then additionally when we have a request then we have a condition of request and a callback function what to add to the query first let's add a parameter of request instead of calling request helper every time like this globally I'm a bigger fan of using a default laravel function of request request which will be Auto resolved with all the get parameters so when we have request date from for example the second parameter is a function which accepts query as a parameter and which should use the global request like this and then inside we add condition to the query so in our case query where starting date is bigger or equal request date from like this and then in a similar fashion we need to add more when conditions which makes it a pretty readable kind of one liner or one sentence so when date two the only thing we need to change is starting date like this and date to here and if you have more conditions then you add more so for example let's duplicate that and add prices here before so price from and we add price from here the only difference is that we need to calculate the price in cents which means we need to multiply that by 100 like this and then similarly price 2 price 2 copy here multiply by 100 and then price should be lower than this times 100. so this is our one condition to filter the data so now let's see we have these three records in the database and now if we add price from 99 and price to for example up to 150 what would be the result we sent and we have only two records and not three so the third one is eliminated which means our Filter Works and with the date we have 10th of June until 19th let's make it 12th of June as you can see starting date is 11 so this should be eliminated Let's test it out we send and we have only one record so this works as well similar or identical fashion is for ordering so one request something we need to order by so when we have request sort by for example then we need to order buy and this will be a parameter so order by which field which is exactly request sort by and we also need to provide sort order which would also be a variable sort order so in fact we need to check both if required sort by and sort order like this so this actually works for example if we get back to two records and sort by Price ascending like this sort by Price descending would be different order so that works the only thing we need to take care of is validation of the parameters so if someone provides invalid values for example string instead of integer or something like for example sort order random it would throw 500 error internal server error and as an API Creator one of your goals is to provide error messages not in 500 status codes but with 400 status codes which means you validate the data and you provide the validation error with as clear as possible message to the API client so let's do exactly that how can we validate that one of the approaches could be validated inside and then do not initialize order by y if the parameter is not within the valid value so for example if not in Array request sort order of ascending or descending then we just return which would not fire this order by so if we now do sort order random it would just not sort so this is one approach but if you want to throw a typical validation error with 422 status code let's make it a proper validation again there are a few ways as usual in laravel we have request variable here request object and one of the ways to fire the validation in laravel is request validate and inside you have validation rules so what rules we have for price from it should be integer or numeric I think it is called similarly price 2 is numeric than date from is date similarly date two is date and then four sort by for now we allow that to be just price but then maybe in the future there will be more fields to sort by so we need to use rule in and then array of possible values in our case for now it's just the price but for sort order it would be the same rule in but with two values ascending or descending and that rule is automatically added by my phpstorm here on top like this and by the way we don't need that thing anymore phpstorm underlines it as not used anymore so yeah we have request validate here and now if we put in random order here see the result 422 status code with proper error message for the front end but in fact this message can be also improved selected sort order is invalid but what is valid so invalid is the default error message by rule in but we can add more validation messages customize them by providing second parameter of request validate which is array of messages so sort by if the validation rule fails for sort by field the message would be for example I will paste it from my notes the sort by parameter accepts only price value like this similarly in sort order if something happens with sort order the sort order parameter accepts only ascending or descending value like this and now relaunch again and as you can see the message is much more readable in more human language and final thing what I would do here I don't like validation in controllers this is a personal preference but I'm a big fan of form request classes and you can use form request class success even if it's not a real form so that's one thing that you may not know and then another thing yes you can use form requests on get requests as well not only on post or put requests so we can generate PHP artisan make requests let's call it tours list request like this so we have that class we open that request by default authorize is true and then we just cut and paste validation rules which are here so cut from here based into rules and then also autocomplete by phpstorm and also Define a method called messages which would return the array of error messages like this so we cut that one as well and paste return array here and also array here just for good practice and now we don't need to validate anything here we don't need requests here instead of that request we use tours list request and on top we should be replacing probably these two are not needed anymore so in this way the controller is cleaner and it's kind of separation of concerns so controller takes care of the parameter processing and validation is separately in a separate class which takes care of validation this is my personal preference just to make sure relaunch the validation error is still here and if we provide a proper parameter then the results are here still works great the final thing in this lesson is automated tests as usual and we have tours list test file we need to add more methods here to test the filtering test the sorting and test that validation actually happens and in this case to save you some time I will just paste the actual test methods here and and will comment them one by one instead of me just typing everything because there won't be much new here to be honest so here we go I've pasted the methods from my notes and we test that the tours list sort by starting date correctly without any parameters so we create travel we create later through an earlier tour and variable names are important generally in tests for them to be readable so someone else in the future would understand what are we actually testing we are testing that data zero which is the first element contains earlier tour and data one contains later tour so it's not just tour one and two or two and then we add more parameters sorts by Price correctly and this test is actually two in one we test that the cheap tour is earlier than expensive tour before expensive tour and also if we have two cheap tours we're still sort by starting date and then for the filter test filters by Price correctly we also create two records again variable most expensive tour and cheap tour and we fire some end points with various parameters so price from price from bigger price two and then we assert that some fragment exists or missing the only thing interesting here is since we're using the same endpoint multiple times within the same method I decided to transform it into a variable also you may refactor that into a variable private variable of the full tours list test class and then use this endpoint everywhere that's also possibility and personal preference and then filter by starting date also similar fashion endpoint a lot of calls for that endpoint and assert that something is correct or incorrect and finally quick test for validation errors if we provide date from or price from as invalid strings we return four to two status code and now for launch PHP Artisan test now we have 10 tests in 10 methods into class so that's it with this end point the next lesson will be about creating users who would then manage that data for these endpoints
Info
Channel: Laravel Daily
Views: 4,034
Rating: undefined out of 5
Keywords:
Id: G-bz_FIcczg
Channel Id: undefined
Length: 12min 30sec (750 seconds)
Published: Sun Jun 11 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.