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.

php Courses
php Courses
php Courses
Capturing Route Parameters and Query String Parameters Simultaneously in Laravel

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:

class PostController extends Controller
{
    public function content($id)
    {
        // $id contains the value from the URL
    }
}

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:

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
    }
}

Optional parameters : Laravel routes can include several optional segments, e.g.:

Route::get('/article/{id}/{source?}/{medium?}/{campaign?}', 'ArticleController@detail');

In the controller, define default values for the optional parameters:

public function detail(Request $request, $id, $source = '', $medium = '', $campaign = '')
{
    // $source, $medium, $campaign receive values if present in the URL
}

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPLaravelquery stringOptional ParametersRoute Parameters
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.