Eric Schumann Eric Schumann - 5 days ago 5
PHP Question

Routing conflict Laravel

I have two routes set up, where one takes an argument and another is just a URL that should route to a form where a new User can be created. However, when I navigate to /users/create it seems like my getUser function is receiving the get request and sending me to my user.blade.php instead of my createUser.blade.php.

Route::get('/users/{id}', "UserController@getUser");
Route::get('/users/create', "UserController@createUser");


My methods in the UserController are:

public function createUser(){
//TODO: Handle user creation.
return view('createUser');
}

public function getUser($id){
$user = User::find($id);

return view('userdetails', compact('user'));

}

Answer

A better and much safer approach for handling this is

Route::get('/users/{id}', 'UserController@getUser')->where(['id' => '[0-9]+']);
Route::get('/users/create', 'UserController@createUser');

The where() tries to match the id field with a specific regex/regular expression. In this case [0-9] means any integer between 0-9 and + indicates multiple times :)

Comments