Capturing Route Parameters and Query String Parameters Simultaneously in Laravel
This article demonstrates how to define Laravel routes that accept both path parameters and query‑string values, shows the required controller method signatures, and explains handling multiple optional parameters with default values using dependency injection.
The article explains how Laravel can capture route parameters defined in the URL as well as additional query‑string parameters in a single controller method.
Capturing route parameters : Define a route such as Route::get('post/{id}', 'PostController@content'); and retrieve the parameter in the controller with:
<code>class PostController extends Controller
{
public function content($id)
{
// $id contains the value from the URL
}
}</code>Capturing both route and query‑string parameters : For a request like http://example.com.cn/post/1?from=index , inject the Request object before the route parameter:
<code>namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function content(Request $request, $id)
{
$from = $request->get('from'); // retrieves the query‑string value
}
}</code>Optional parameters : Laravel routes can include several optional segments, e.g.:
<code>Route::get('/article/{id}/{source?}/{medium?}/{campaign?}', 'ArticleController@detail');</code>In the controller, define default values for the optional parameters:
<code>public function detail(Request $request, $id, $source = '', $medium = '', $campaign = '')
{
// $source, $medium, $campaign receive values if present in the URL
}</code>An example URL with optional parameters is http://example.com.cn/article/1/wx/h5?param1=val1&param2=val2 , where "wx" maps to $source and "h5" maps to $medium .
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.