27th February 2023
A few days ago, while working on a project where I wanted to use strict types and also have Larastan on the highest level, I needed to pass parameters from within the Laravel Request class into methods that expect a specific type, but the standard input() method on the Request class for retreiving parameters from the request returns a mixed type, which leads to a lot of single use variables just for type casting. Building on my Tweet on the subject, lets take a look at an example
In the above example, imagine a BlogSearchController that could take a search term, or a year posted parameter from the Request URL, but when you go to use those variables later on in methods that expect a certain type, Larastan errors because that method is expecting a string, or an integer. So, to fix that, you extract a couple of variables...
Well, the good news is Larastan now passes, but, the bad news, you've now got six extra lines of code just for two extra variables to keep Larastan happy.... More bad news, the code has lost a bit of that elegance that we're all used to with Laravel....
What if I told you there's a better way?
Did you know that the Laravel Request class also has string(), integer() and even boolean() methods, alongside the input() method we're already using? Did you know that those methods return native types, rather than a mixed type? I didn't until a few days ago, but using those methods we can bring our code back to just three lines...
Look at that, with just one small change from using the input() method to a method that returns a native type, our code has that Laravel elegane back, it's once again back to just three lines, and, Larastan is passing! No more single use variables just for type casting!