Home » Php » php – Laravel 5 – link_to_route() method making my route parameters to change into Query String by adding "?" at the end

php – Laravel 5 – link_to_route() method making my route parameters to change into Query String by adding "?" at the end

Posted by: admin July 12, 2020 Leave a comment

Questions:

After hours of searching I still could not find my answer regarding L5.

What my issue is :

I want to make a link something like this:

localhost:800/songs/you-drive-me-crazy

BUT what is get is:

localhost:800/songs?you-drive-me-crazy

my route parameter is changing into query string.

//routes.php

$router->bind('songs', function($slug)
{
return App\Song::where('slug', $slug)->first();
});


$router->get('songs', ['as' => 'songs.index', 'uses' =>    '[email protected]'] );

$router->get('songs/{songs}', ['as' => 'songs.show', 'uses' => '[email protected]'] );

I am using:

{!! link_to_route('songs.index', $song->title, [$song->slug])  !!}

I have tried everything but not succeeded yet,your suggestion may be helpful.

Thanks.

How to&Answers:

Your usage of link_to_route is incorrect:

{!! link_to_route('songs.index', [$song->title, $song->slug])  !!}

The first parameter is the route name, the second parameter is an array of route parameters, preferably using key value. Because you did not show your defined route, it’s hard to guess what this associative array should look like:

{!! link_to_route('songs.index', ['title'=>$song->title, 'slug'=>$song->slug])  !!}

Also I advise you to use the documented functions: route(), see: http://laravel.com/docs/5.0/helpers#urls

A correctly requested route using route():

{!! route('songs.index', ['title'=>$song->title, 'slug'=>$song->slug])  !!}

A properly formatted route would then be:

Route::get('songs/{title}/{slug}', ['as' => 'songs.index', 'uses' => '[email protected]']);

This will result in a URL like: http://localhost:800/songs/you-drive-me-crazy/slug

If you only want to add the title to the URL but not the slug, use a route like this:

Route::get('songs/{title}', ['as' => 'songs.index', 'uses' => '[email protected]']);

This will result in a URL like: http://localhost:800/songs/you-drive-me-crazy/?slug=slug

Using

Route::get('songs/{slug}', ['as' => 'songs.index', 'uses' => '[email protected]']);

The URL will be like: http://localhost:800/songs/you-drive-me-crazy/?title=title assuming the slug now is you-drive-me-crazy

Any added parameter in a route() call will be added as a GET parameter if it’s not existing in the route definition.

Answer:

fixed it, thanks for your great concerns and suggestions.

I was linking to wrong route here:

`{!! link_to_route('songs.index', $song->title, [$song->slug])  !!}`

now, I changed it as :

`{!! link_to_route('songs.show', $song->title, [$song->slug])  !!}`

and it did the trick.