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

BartHuis's avatar

Passing parameters outside url to shorthand routes

Hi,

When i have the folowing in my routes:

    Route::group(['prefix' => '/something'], function() {
        Route::get('/categories/{id}', ['uses'=>'CategoryController@categoryById']); // returns given category as json
    }
    Route::group(['prefix' => '/categories'], function() {
        Route::get('/{id}', ['uses'=>'CategoryController@categoryByIdView']); // returns given category as view
    });

and this in my category controller:

    public function categoryById ($id) { // returns given product as json
        $category = \App\Category::with('product')->findOrFail($id);
        return response()->json($category);
    }
    public function categoryByIdView ($id) { // returns given product as view
        $category = \App\Category::with('product')->findOrFail($id);
        return viewForDomain('category', ['category'=>$category]);
    }

everything works.

But i like this more in my controller:

    public function categoryById ($id, $format) { // returns given product as given format
        $category = \App\Category::with('product')->findOrFail($id);
        if($format == 'json'){
            return response()->json($category);
        }
        else if($format == 'view'){
            return viewForDomain('category', ['category'=>$category]);
        }
    }

But, if i want to keep the shorthand notation in my routes, is it possible to pass an extra parameter to the function, without adding it to the route path? I think i need something like:

    Route::group(['prefix' => '/something'], function() {
        Route::get('/categories/{id}', ['uses'=>'CategoryController@categoryById','format'=>'json']); // returns given category as json
    }
    Route::group(['prefix' => '/categories'], function() {
        Route::get('/{id}', ['uses'=>'CategoryController@categoryById','format'=>'view']); // returns given category as view
    });

off course this is some dummy code, that gives:

Missing argument 2 for App\Http\Controllers\CategoryController::categoryById()

How can i do something like this? or do i have to skip the shorthand at this point and add the function way of writing here?

Bart

0 likes
29 replies
usama.ashraf's avatar

You'll have to specify the parameter. You might be able to send the extra parameter in the request body but this is a GET request so avoid that.

Why not do this:

Route::get('/categories/{format}/{id}', ['uses'=>'CategoryController@categoryById']); 
BartHuis's avatar

@usama.ashraf yeah, but i don't want the format in the url ;) that why the title is

"Passing parameters outside url to shorthand routes"

and the topic says:

"without adding it to the route path?"

;) any other way to pass it to the shorthand way? or do I have to use the function way of making the route and pass the format there?

SaeedPrez's avatar

What you like is not good practice because it makes your code harder to follow/read and it puts another layer (more logic than necessary) into a single controller method.

Prullenbak's avatar

why not use the wantsJSON() method?

public function show(Request $request, $id) {
        $category = \App\Category::with('product')->findOrFail($id);
    if($request->wantsJson()) {
                return response()->json($category);
    }
        return viewForDomain('category', ['category'=>$category]);
    }
1 like
ricardovigatti's avatar

Don't you think you're messing up with things? Sorry if this looks like ofensive (belive me, i don't want to be..).

It seems you are doing an API inside your application. I understood that calling the api url, will return the result as JSON and calling the application route, will return the result as a View.

If it's really what you wanna achieve, i can give you a hint.

BartHuis's avatar

first, at laravel.io i posted it too, voyowsky gave a example of just putting it in a function in the routes, i edited that one from his suggestion, and that is indeed working (i allready thought about this myself too, but wanted to try shorthand first):

    Route::group(['prefix' => '/something'], function() {
        Route::get('/categories/{id}', function ($id) {
            $controller = new \App\Http\Controllers\CategoryController();
            return $controller->categoryById($id, 'json');
        }); // returns given category as json
    }
    Route::group(['prefix' => '/categories'], function() {
        Route::get('/{id}', function ($id) {
            $controller = new \App\Http\Controllers\CategoryController();
            return $controller->categoryById($id, 'view');
        }); // returns given category as view); // returns given category as view
    });

but it would be nice if someone still can come up with a shorthand method to do this, this way it would almost be more efficient to put everything from the controller function directly to this function, while my intension is to put as much as possible outside the controllers :)

Then, the other replys here at laracast:

@SaeedPrez : is it? it keeps my routes file nice and tiny, every logic is in the controller now.

@Prullenbak : i didn't know that one, ill take a look at it.

@ricardovigatti : yes, actually it is for api and non api ;) but, i saw some exemples earlier where the api was totaly apart from the app, while my api and views are almost the same, only an other rendering... so thats why i called it "something" first ;P but, if you have some hints for me how to handle the api part in such a way that i can seamlessly program api and views along eachother and not totaly diferent places, i'll love to hear ;) this is all programming in the raw stadium where i'm looking for best practices to setup our app ;)

Thanks for all response ;)

Bart

ohffs's avatar

Just an aside, but what does 'in the raw stadium' mean (or suggest)? I've never read that and can't quite place the image into another metaphor :-) I'm always fascinated by metaphors/imagery in other languages :-)

ricardovigatti's avatar

I was going to say for you discern the API from your application, kkkk. Sometimes i do it, i build de API as my main project, than, at another namespace i build the application using the API, yuknow?

As you said that you won't do this, nevermind. Each project has their own different aproaches.

Aside this, i like the way you handled the "route function way".

BartHuis's avatar

@ohffs haha yeah, i'm not really good in explaining myself in english sometimes, as @SaeedPrez said, early stages. what i wanted to say is that i'm still able to change everything, but much things i allready thought about how i want to handle it, sometimes with a reason, sometimes not ;P so thats why i sometimes don't share all the code to not confuse everyone here with all the other code.

@SaeedPrez I'll take a look at that code and how api's are handled in the standard way, and if it's usable in this case.

@ricardovigatti The api is just an extra, the app part is the biggest one, so building the api as main project and use it in the other parts don't seem very logical to me, but i can imagine in some cases it is.

BartHuis's avatar

@Prullenbak @ohffs @SaeedPrez @ricardovigatti : when searching for the wantsJson() i see its removed from the latest docs, but is still available as code. but when searching for implementations and api implementations, i end up in old way's everywere. does someone has a good laravel 5 tutorial where the api is not the base but just a side service?

ricardovigatti's avatar

I don't know about any tutorial. But don't worry. If you are going well that way, there is no need to bore about other ways. Continue until you surelly see a need for upgrading your structure.

BartHuis's avatar

i found something here, nice bould up of the code including doing this the simple wrong way first, and then bit by bit refactoring it, just like i'm doing at the moment:

https://laracasts.com/series/incremental-api-development

but thats old code, and something here:

http://www.tutorials.kode-blog.com/laravel-5-rest-api

using laravel 5, but thats using the same ::all as i did at the moment, while the first link is saying thats not good. so something like the first one, but then in a laravel5 version would be nice :D

BartHuis's avatar

@ricardovigatti thnx, it would work, yes. but as the others say, there are other way's of implementing the api part. for now i can continue on this way, but it would be nice if an more standard way is applicable to this project ;)

ricardovigatti's avatar

Yeah, that first link seems to be a great course, but i only have access to the first video, cause i don't have subs.

This course can payback, even being target of Laravel 4, sometimes the idea behind the code is more important than the code itself.

BartHuis's avatar

@ricardovigatti yeah, if there wil be no outcome here, ill watch the rest, but in the first video i allready see so much old things. plus the fact, that maybe in 5 there will be an other point of view? its strange that the whole wantsjson function is removed from the docs right?

BartHuis's avatar

btw, i have an paid account here, so i could watch the rest ;)

@ricardovigatti i saw in my mail you just posted this one, but now its deleted? "I think it was replaced by the $request->ajax() method. I don't know if they actually do the same thing, but i saw that people are using more the ajax() method now."

thats my main question now. what is the overal vision from laravel what is the best way for API implementation?

Bart

ricardovigatti's avatar

kkkkk i'm sorry for this.. I thought well about my post. Those methods are look alike but they can't be replaced by each other since they do different things.

I don't like to treat things as being "Laravel way", i know that if, we are using the framework X or Y, is good to keep yourself on their most common sintaxes and implementations. But laravel's developers made a great job delivering an uncoupled structure, letting us decide how to implement our features.

What i want to say is: maybe there is no "Laravel best way" to do, u know?

In otherside, if you're referencing "Laravel" as the community, yeah, maybe there is preferences for a way or another, but you, as a member of this community, has a portion on the final decision.

Another thing. A lot of times i reach in other communities, other languages or others frameworks, searching for this kind of opinion. It's good because you can create your own solution within a world wide overview, not only from the PHP or Laravel.

BartHuis's avatar

That makes sense... allthough if everybody is used to do it in one way in laravel, its good to do it the same some other programmers could be easyly step in when hired in for this project when you could say, it's a laravel project... but i understand you too, and it's a good thing for sure... only now i'm doubting, let it this way, or leard about that request thing, where i couldn't find good laravel5 examples for...

BartHuis's avatar
BartHuis
OP
Best Answer
Level 2

just told at laracon, about 5.3:

Alyssa July 27, 20164:07 Pm 1 – changes to the folder structure.

Eric L. Barnes July 27, 20164:07 Pm Splitting up the routes file into web.php and api.php

looks like there actualy are thoughts about api? ;)

BartHuis's avatar

yeah, i heard that one. but thats just the place where the route file(s) live. not implementing it as an api ;)

BartHuis's avatar

nice one by the way, the 2x2 idea... only a bit difficault when working on office ;P

BartHuis's avatar

@Prullenbak but, is there a "jeffrey way"? or do you mean the video series i mention with the old code and refactor that to the new one?

Please or to participate in this conversation.