Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Knumskull's avatar

Generating a route with a query string parameter

Is there any way to build a url with a query string directly, without using ugly concatenation?

<a href="{{ action('topics.show', [$topic->forum->category->id, $topic->forum->id, $topic->id]) . '?page=' . $topic->posts_paginated->getLastPage() }}">

Currently i'm doing this, but I find it ugly.

0 likes
5 replies
Devon's avatar
Devon
Best Answer
Level 18

Yes, but it won't clean up the code very much... Also, the 1st argument you're passing in is not an action, it's a route name...

For something like this, I'd probably create a macro or a partial to keep my template from becoming too hard to read.

Working with Laravel URLs

link_to_route

To get started, you can use link_to_route()...
link_to_route($name, $title = null, $parameters = array(), $attributes = array())

// routes.php
Route::get('/topics/{category}/{forum}', [
    'as'   => 'topics.show',
    'uses' => 'TopicsController@show'
]);

// *.blade.php
{{ link_to_route('topics.show', 'Link Text', [ 
    $topic->forum->category->id,
    $topic->forum->id,
    'page' => $topic->posts_paginated->getLastPage() 
 ]); }}

link_to_action

If you want to use an action, link_to_action() is very similar, except it uses the action instead.
link_to_action($action, $title = null, $parameters = array(), $attributes = array())

Given the same Route as above, you'd use...

// *.blade.php
{{ link_to_action('TopicsController@show', 'Link Text', [ 
    $topic->forum->category->id,
    $topic->forum->id,
    'page' => $topic->posts_paginated->getLastPage() 
 ]); }}

Result & Explanation

Both examples above will generate:
<a href="http://domain.tld/topics/23432/5434?page=2">Link Text</a>

Basically, anything after the expected number of parameters is exceeded, the remaining arguments are added as a query string.

Note

If you don't want to generate the HTML too, you can just use route() or action() respectively.

6 likes
sidscorner's avatar

It's very simple. Generate the URL like you would with route parameters. Laravel will automatically append them as query strings.

Say your route looks like this:

Route::get('/{id}, array('as' => 'test.route', function($id){
    return $id;
}));

You would generate a link like this in your view:

<a href="{{ route('test.route', array('id' => 1,  'something' => 'here',  'another' => 'there')) }}">click here</a>

Your url would look like this:

http://localhost:8000/1?something=here&another=there
14 likes

Please or to participate in this conversation.