1

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
  • Route::get('articles/category/{cat}', function($value){ return $list = App\Article::where('category','=',$value')->first(); }) Commented Oct 30, 2015 at 22:46

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I personally like to add a pattern if it's something that is fairly standard, like Route::pattern("id", "[0-9]+"); Seems to keep routes a bit cleaner.
Yes, you can add a global pattern, Check the Global Constraints section.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.