doutu4335
doutu4335
2019-02-27 09:08
浏览 160
已采纳

Laravel在同一个控制器中显示多个功能

i have a problem with making a newswebsite. I have multiple index functions to load in category views. inside of each view i want to be able to go to an article page by using the show function. how do i use multiple show functions within one controller.

these are 2 of the 8 index funtions i use.

public function indexbusiness()
{
    $artikels =  Artikel::where('category_id', '4')->get();
    return view('pages.business')->with('artikels', $artikels);
}

public function indextech()
{
    $artikels =  Artikel::where('category_id', '5')->get();
    return view('pages.tech')->with('artikels', $artikels);
}

i want to add show functions like this

 public function showbusiness($id)
{
    $artikel = Artikel::find($id);
    return view(pages.show);
}

can someone help me out on this one?

all help is appreciated

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanou3868
    duanou3868 2019-02-27 09:34
    已采纳

    I would go about this from a different approach. You can use just one controller for this and accept a category as a parameter. For example in your routes:

    Routes

    Route::get('/articles', 'ArticlesController@index');
    Route::get('/articles/{category}', 'ArticlesController@index');
    

    Within your controller, you would then have one index method. For example:

    ArticleController

    public function index($category)
    {
        if($slug) {
            $articles = Article::whereHas('category', function ($query) use ($category) {
                $query->where('slug', $category);
            })->get();
    
            return view('pages'.$category)->with('articles', $articles);
        }
    
        $articles = Article::all();
    
        return view('pages.articles')->with('articles);
    }
    

    That will allow you to load which ever articles you want by the category. This approach makes the assumption that you have a relationship of category on the Article model and that the Category model has a slug value.

    For this example, you could then visit /articles/tech or /articles/business.

    You can then do the same approach with the show method. For this, your routes might look like the following:

    Routes

    Route::get('/articles/{category}/{article}', 'ArticlesController@show');
    

    Your controller could then be

    ArticleController

    public function show($category, $id)
    {
        $article = Article::whereHas('category', function (query) use ($category) {
            $query->where('slug', $category);
        })->where('id', $id)->first();
    
        return view('pages.show')->with('article', $article);
    }
    

    You might need to adapt the above to fit your specific use case, but the principle is generally the same.

    点赞 评论

相关推荐