Laravel custom controller method calling

时间:2015-10-30 22:23:53

标签: php laravel routing

I need basic help, as I am new to Laravel.

Situation

I have a controller ArticlesController which has index method which lists all articles and it's working fine. This route below, allows me to show individual articles by 'id' like this articles/id example articles/35 . But i also need to show all articles from category "Swimming" . When I hit articles/swimming it will look for id=swimming. But I don't know how to make custom route to list all articles from "Swimming" category. I have made a method "swimming" inside controller but I need help with route?

  Route::bind('articles', function($value, $route) {
     return $list = App\Article::whereid($value)->first();

    });

1 个答案:

答案 0 :(得分:3)

You can easily create/use two separate routes, one for articles by id and another for articles by category, so for example, routes could be declared like:

Route::get('articles', 'ArticleController@index');

Route::get('articles/{id}', 'ArticleController@getById')->where('id', '[0-9]+');

Route::get('articles/{category}', 'ArticleController@getByCategory')->where('category', '[A-Za-z]+');

Then you may use Controller Methods like (in ArticleController.php):

public function index()
{
    return App\Article::all();
}

public function getById($id)
{
    return App\Article::whereId($id)->first();
}

public function getByCategory($category)
{
    return App\Article::with(['category' => function($q) use($category)
    {
       $q->where('category', $category);

    }])->get();

}

This is just a basic idea, you can improve it, anyways.