Route::get('user/{id}', function($id)
{
return 'User '.$id;
});
Note: Route parameters cannot contain the
-
character. Use an underscore (_
) instead.
Route::get('user/{name?}', function($name = null)
{
return $name;
});
Route::get('user/{name?}', function($name = 'John')
{
return $name;
});
Route::get('user/{name}', function($name)
{
//
})
->where('name', '[A-Za-z]+');
Route::get('user/{id}', function($id)
{
//
})
->where('id', '[0-9]+');
Route::get('user/{id}/{name}', function($id, $name)
{
//
})
->where(['id' => '[0-9]+', 'name' => '[a-z]+'])
If you would like a route parameter to always be constrained by a given regular expression, you may use the pattern
method. You should define these patterns in the boot
method of your RouteServiceProvider
:
$router->pattern('id', '[0-9]+');
Once the pattern has been defined, it is applied to all routes using that parameter:
Route::get('user/{id}', function($id)
{
// Only called if {id} is numeric.
});
If you need to access a route parameter value outside of a route, use the input
method:
if ($route->input('id') == 1)
{
//
}
You may also access the current route parameters via the Illuminate\Http\Request
instance. The request instance for the current request may be accessed via the Request
facade, or by type-hinting the Illuminate\Http\Request
where dependencies are injected:
use Illuminate\Http\Request;
Route::get('user/{id}', function(Request $request, $id)
{
if ($request->route('id'))
{
//
}
});