Last active
March 4, 2018 23:57
-
-
Save stevenspads/cccf35d8c19fc051c37052c3be745d0f to your computer and use it in GitHub Desktop.
Using Request for Laravel Route::get() controller functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Here's what my web.php file looks like with a locale prefix on all routes for a multilingual app. | |
// To manage the locale, I'm using two middlewares: | |
// the 'locale.default' middleware to set a default locale, | |
// and the 'locale' middleware to call app()->setLocale($segment) on the first request segment. | |
// The two middlewares appear to be working fine. | |
Route::prefix('{locale?}')->middleware(['locale.default', 'locale'])->group(function() { | |
Route::get('/car/{id}', [ | |
'uses' => 'CarController@getCar', | |
'as' => 'car', | |
'middleware' => 'auth' | |
])->where(['id' => '[0-9]+']); | |
}); | |
// Problem: In CarController's getCar($id) function, the $id parameter has the locale (en, fr, it) instead of | |
// the actual id of the car being passed. | |
public function getCar($id) | |
{ | |
$car = Car::where('id', $id)->firstOrFail(); | |
} | |
// I could do the following but it adds the extra unnecessary passing of a $locale parameter everywhere, so I'll avoid this. | |
public function getCar($locale, $id) | |
{ | |
$car = Car::where('id', $id)->firstOrFail(); | |
} | |
// If I change getCar()'s parameter from $id to $request of type Request, I can successfully do the following. | |
public function getCar(Request $request) | |
{ | |
$car = Car::where('id', $request->id)->firstOrFail(); | |
} | |
// Is this a good solution? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment