Tom Barton Tom Barton - 6 months ago 23
PHP Question

Passing "\" and "/" in variable via Laravel Route

First off, apologies if this is a bad question/practice. I'm very new to Laravel, so I'm still getting to grips with it.

I'm attempting to pass a variable that contains forward slashes (/) and backwards slashes () in a Laravel 5 route and I'm having some difficulties.

I'm using the following:

api.dev/api/v1/service/DfDte\/uM5fy582WtmkFLJg==
.

Attempt 1:

My first attempt used the following code and naturally resulted in a 404.

Route:

Route::group(array('prefix' => 'api/v1'), function() {
Route::resource('service', 'ServiceController');
});


Controller:

public function show($service) {
return $service;
}


Result:

404


Attempt 2:

I did a bit of searching on StackOverflow and ended up using the following code, which almost works, however, it appears to be converting \ to /.

Route:

Route::group(array('prefix' => 'api/v1'), function() {
Route::get('service/{slashData}', 'ServiceController@getData')
->where('slashData', '(.*)');
});


Controller:

public function getData($slashData = null) {
if($slashData) {
return $slashData;
}
}


Result:

DfDte//uM5fy582WtmkFLJg==


As you can see, it's passing the var but appears to be converting the \ to /.

I'm attempting to create an API and unfortunately the variable I'm passing is out of my control (e.g. I can't simply not use \ or /).

Does anyone have any advice or could point me in the right direction?

Thanks.

Answer

As you can see from the comments on the original question, the variable I was trying to pass in the URL was the result of a prior API call which I was using json_encode on. json_encode will automatically try and escape forward slashes, hence the additional \ being added to the variable. I added a JSON_UNESCAPED_SLASHES flag to the original call and voila, everything is working as expected.