I image this is a simple one. I have a url like '../area/England' and '../area/United%20States' that I want to be '../area/england' and '../area/united-states' respectively.
These areas are stored in my database as 'England' and 'United States'. I was thinking I could store them as the value I want which would be good for the urls ('england' and 'united-states'), but then I would have to convert them back to the original when I display them on the page (ex. 'Welcome to United States!'). So this option is not great as I will have to do conversion anyways.
So my questions are, 1. What is the best practice to do this type of url manipulation? And 2. Where do I put my code? (strtolower and str_replace)
Thanks
Check out the "Customizing the resolution logic" section of https://laravel.com/docs/5.2/routing#route-model-binding
In your route:
Route::get('/area/{country}',function(Country $country){})
Then in your RouteServiceProvider::boot
method, you can write a statement like this:
$router->bind('country', function ($value) {
return Country::where('name', strtoupper(str_replace("-"," ",$value))->first();
});
However, converting a URL slug to a country name might not always work like this. If you can't write a function that reliably converts a slug to a country name, then you should create a new database column called slug
and then use:
$router->bind('country', function ($value) {
return Country::where('slug', $value)->first();
});
I guess you could also pull the whole list of countries and sort through them, doing str_replace
and strtolower
until you find a match, caching the country results for awhile each time. Less efficient though, I would make a slug column.