I’m working on a Laravel application that basically lets users make collections of eBay products. For those collection I use a model called
ProductList. I initially wanted to call that model simply
List, but that is a php reserved word.
Because I wasn’t happy with how wordy Product List sounds, I decided to name my route simply
lists. I can view all lists going to
GET /lists, or
POST to that same url to make a new list, but when I tried to got to
GET /lists/1 to view the first list, I would not get what I expected. Instead of a populated
ProductList model in my controller, I was getting an empty model. The first symptom I saw was that trying to output the list name in my blade template resulted in nothing being printed out.
This got me scratching my head for a little bit. The controller’s method was well declared, so I referred to the documentation to see what might be going wrong. None of my previous experiences working with Laravel had had this kind of issue, but looking at the docs is always a good start.
The documentation states “Laravel automatically resolves Eloquent models defined in routes or controller actions whose type-hinted variable names match a route segment name”. The important part here is “whose type-hinted variable name match a route segment”. The
show method of the controller created using artisan had a variable type-hinted as
$productList. Now I just had to check if the route segment matched that name. For doing that, since my routes file uses the resource method to declare the
lists route which means I can’t see the route in the routes file, all I had to do was
php artisan route:list on the command line, and the list of all routes was printed out. Sure enough the route segment, and the type-hinted variable didn’t have a matching name. All I had to do now was edit the
show method’s signature so that the type-hinted variable had a matching name with the route segment. After doing that, everything worked just fine.