【问题标题】:Using Laravel controller to show same items on different pages使用 Laravel 控制器在不同页面上显示相同的项目
【发布时间】:2021-10-26 18:22:51
【问题描述】:

我已经使用 laravel 创建了一个 Web 应用程序。该应用程序是博客网站和电子商务商店的组合。在索引页面上,我制作了一个博客控制器和产品控制器,分别在索引页面上显示 3 个博客项目和 4 个产品项目。现在,我还为博客创建了一个单独的页面,其中将显示网站中的所有博客(3 个博客),并为将显示所有产品(5 本书)的产品创建了一个单独的页面。

我想问是否有一种方法可以使用相同的控制器(产品控制器)在索引页面和产品页面上显示不同数量的产品。通过使用循环或其他方式。

这是我用来在索引页面上显示产品的代码,它在索引页面上显示 4 个产品。如果您有任何可以帮助我的资源,请链接它们。

Product::factory()->count(4)->create();

【问题讨论】:

    标签: php laravel laravel-8


    【解决方案1】:

    在创建任何类型的代码时使用 DRY 方法。

    创建一个可以重复使用的函数。

    public function index(){
        $blogs = $this->getBlogs(3); //Parameterized getblogs() which return only 3 blogs
        $products = $this->getProducts(4); //Parameterized getProducts() which return only 4 products
        return view('index', compact('blogs', 'products'))
    }
    
    
    public function product_view() {
        $products = $this->getProducts(9);
        return view('product', compact('blogs', 'products'))
    }
    
    //this function required one integer value which be will use to fetch that number of products
    //If this kind of function will be used by another class file then you should define this function in any service container or as a helper or In the model itself. so this function can be used by other classes as well.
    public function getProducts(int $limit) {
        return Product::take($limit)->get()
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-07
      • 2014-11-09
      • 1970-01-01
      • 1970-01-01
      • 2013-05-31
      • 2012-01-02
      • 1970-01-01
      • 2017-01-18
      相关资源
      最近更新 更多