Reputation: 7674
Im comming from CodeIgniter.
There if you had a controller like this:
class Article extends CI_Controller{
public function comments()
{
echo 'Look at this!';
}
}
You could access the comments()
function using the URL like this: example.com/Article/comments
Route::get('/Article/comments}', 'ArticleController@comments');
But I was hoping for a more dynamic way to do it as I don't want to keep on creating new routes for every function
Upvotes: 1
Views: 6689
Reputation: 1519
I'll recommend that you stick with the laravel's way to create REST controllers
, because that way you can have control over what HTTP Verb
is being called with the controller method. The laravel way of doing this is just to add the HTTP Verb
in front of the controller method, for your method comments
if you want to specify a GET
request in Laravel the name of the method would look like getComments
.
For example, if you need to do a GET
request for the article/comments
URI, and then to create a new comment you want to use the same URI with another HTTP
verb, lets say POST
, you just need to do something like this:
class ArticleController extends BaseController{
// GET: article/comments
public function getComments()
{
echo 'Look at this!';
}
// POST: article/comments
public function postComments()
{
// Do Something
}
}
Further reading: http://laravel.com/docs/controllers#restful-controllers
Now for your specific answer, this is the Laravel way of doing what you requested:
class ArticleController extends BaseController{
public function getComments()
{
echo 'Look at this!';
}
}
and in the routes.php
file you'll need to add the controller as follows:
Route::controller('articles', 'ArticleController');
Upvotes: 1
Reputation: 87789
The recommended way of dynamically calling controllers methods via URL, for Laravel users, is via RESTful Controllers:
<?php
class ArticleController extends controller {
public function getComment()
{
return 'This is only accesible via GET method';
}
public function postComment()
{
return 'This is only accesible via POST method';
}
}
And create your route using telling Laravel this is a RESTful Controller:
Route::controller('articles', 'ArticlesController');
Then if you follow
http://laravel.dev/articles/comments
Using your browser, you should receive:
This is only accesible via GET method
The way you name your controllers methods (getComment, postComment, deleteComment...) tells Laravel wich HTTP method should be used to call those methods.
Check the docs: http://laravel.com/docs/controllers#restful-controllers
But you can also make it dynamic using PHP:
class ArticlesController extends Controller {
public function comments()
{
return 'Look at this!';
}
public function execute($method)
{
return $this->{$method}();
}
}
Use a controller like this one:
Route::get('Article/{method}', 'ArticleController@execute');
Then you just have to
http://laravel.dev/Article/comments
Upvotes: 3