kwebble's avatar

Can you create a route directly to a class method?

As a Laravel beginner I could not find how to create a route to a specific method of a class. The documentation mention the use of a string, but does explain what the format of the parameter. I tried something like this:

Route::match(['get', 'post'], '/someroute', '\my\namespace\Class@method');

The result is an error:

Call to undefined method my\namespace\Class::getMiddleware()

For now I created a closure that instantiates the class and calls the method, but it would be nice if Laravel can do that. Can anyone describe how?

0 likes
4 replies
bobbybouwmann's avatar
Level 88

You can do something like this

// app/Http/Controllers/MyController.php

Route::get('some-route', 'MyController@method');

However Laravel is expecting you to use the app/Http/Controllers directory for these classes. So everything in there will match the above route.

You can also create sub directories in the Controllers directory and call them by doing this

// app/Http/Controllers/Directory/MyController.php

Route::get('some-route', 'Directory\MyController@method');

If you want to use a complete different directory or location, you need to change the RouteServiceProvider as well, I can give you an example on that as well if it is necessary. These changes might be too advanced for you!

martinbean's avatar

@kwebble Why aren’t you placing controllers in the app/Http/Controllers directory? It’ll make your life much easier, especially if you’re a beginner.

1 like
kwebble's avatar

A new controller can go in app/http/Controllers. But when I saw an example of the action parameter with a string I thought it could work without an extra controller. The only thing the controller would do is create an instance of the class I use and invoke the method.

Some background: this is to migrate an existing application to Laravel. The first step is to embed it completely in a Laravel application with as little changes as possible. When that is working the new version can be used.

The next steps are then to migrate functions one by one from the old version to the new.

@bobbybouwmann: for my own namespace I expect a mapping in RouteServiceProvider::map is required. By the way, that map method looks a bit hacky to me, requiring a different file directly inside a class method...

bobbybouwmann's avatar

You can of course register you own namespace in the RouteServiceProvider, but that is up to you. I would go with the simple route and simple create the controllers right now ;)

Please or to participate in this conversation.