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

kylestev's avatar

Using .filetype in routes.

Hey,

I am writing a Laravel 5 app with a REST API as the backend and a frontend displaying results from said API.

I was looking into ways of putting a file type in the url for requests like this:

/subjects/primarykey.json

If the same route with the .json postfix was requested (/subjects/primarykey), it would display the html view.

I was imagining some sort of route middleware might be used to remove the .json from the url before it is passed to my controllers, but it doesn't seem possible to modify the Request object's url.

Anyone dealt with this before?

Here's an ugly proof of concept using php's reflection:


class AllowDotJson implements Middleware { // ... /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if ($request->is('*.json')) { $reflectionClass = new \ReflectionClass('\Illuminate\Http\Request'); $prop = $reflectionClass->getProperty('pathInfo'); $prop->setAccessible(true); $path = $prop->getValue($request); $prop->setValue($request, substr($path, 0, -5)); $prop->setAccessible(false); } return $next($request); } }
0 likes
2 replies
kylestev's avatar

@MThomas thanks for the reply!

I think I'll take the approach of reading the Accept header. I was mostly just curious on how to use it with Resource Controllers -- didn't mention that in the OP.

Please or to participate in this conversation.