Patrick Bolter
Patrick Bolter

Reputation: 13

Laravel 4.2 link to action links & as %27

hello I have the following line:

{{ link_to_action('FriendController@add', 'Friend ' .explode(" ", $user->name)[0],[Auth::user()->id,$user->id]) }}

and a route defined as

Route::post('friend/add{id}&{fid}', ['as' => 'friend.add', 'uses' => 'FriendController@add']);

however the url isn't parsing the 2 arguments correctly as it comes up as /add1%262 instead of /add?1&2

I cant figure out why, it was working before. Also it comes up with method [show] does not exist when it does go through.

Upvotes: 1

Views: 354

Answers (1)

Bogdan
Bogdan

Reputation: 44526

There are two problems here, that fail to match your expectations about what is supposed to happen:

1. The first and most importat one, is that the link_to_action helper function uses the to method in the Illuminate\Routing\URLGenerator class to generate the URL, which in turn makes use of the rawurlencode method that will encode reserved characters according to RFC 3986. Since the & character is a reserved sub-delimiter character it will automatically get encoded to %26, which will result in your URL path looking like this /add1%262.

2. The second issue is that you define your route path like this friend/add{id}&{fid}, yet you expect it to have a ? in there. Even if you were to add it the route definition like so friend/add?{id}&{fid}, it would still not work because ? is a delimiter character and will get encoded as well, so you'll end up with /add%3F1%262.

The central issue here is that you should not be defining query string parameters in your Laravel route definition. So you either move the parameters from the route definition to the query string and build your HTML link and the URL manually:

// routes.php
Route::post('friend/add', ['as' => 'friend.add', 'uses' => 'FriendController@add']);

// Your Blade template
<a href="{{ action('FriendController@add') }}?{{ Auth::user()->id }}&amp;{{ $user->id }}">
    Friend {{ explode(" ", $user->name)[0] }}
</a>

Or change the route definition so it doesn't contain any reserved characters that might get encoded:

// routes.php
Route::post('friend/add/{id}/{fid}', ['as' => 'friend.add', 'uses' => 'FriendController@add']);

// Your Blade template
{{ link_to_action('FriendController@add', 'Friend ' .explode(" ", $user->name)[0],[Auth::user()->id,$user->id]) }}

That being said, even with your current setup that generates the path /add1%262, Laravel would still know to decode the parameters, so in your controller action method you'll still get 1 and 2 as the user IDs:

public function add($id, $fid)
{
    // $id = 1
    // $fid = 2
}

Upvotes: 2

Related Questions