How to fetch 2 products from every category

I want to fetch 2 products from every category.

Product.php

class Product extends Model
{ 
   protected $table = 'products';
}

Category.php

class Category extends Model {
    protected $table = 'categories';
}

Controller

public function index() {
    $products = Product::all();
    return Product::latest()->take(5)->get();
}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

This should fetch the first two products of each category:

// Get all categories
$categories = Category::all();

//Create an empty array to store our product IDs
$prodIds = array();

// Extract the first 2 product IDs in each category
foreach ($categories as $category) {
    $prodIds[] = $category->products->take(2)->pluck('id');
}

// Fetch products from their IDs
$products = Product::findMany($prodIds);

Edit: Also my answer above should work, it will fail if the category doesn’t have at least two products. To fix this, you would need to remove empty values from $prodIds.

Method 2

Product.php

class Product extends Model
{ 
   protected $table = 'products';

  public function Category()
    {
        return $this->belongsTo(Product::class);
    }
}

Note : import your category model in Category model

Category.php

class Category extends Model {
    protected $table = 'categories';

    public function Product()
    {
        return $this->hasMany(Product::class);
    }
}

Note : import your category model in Product model

Controller

public function index() {
   
    return Category::with('Product'=>funcation($obj){
        return $obj->take(2);
    })->latest()->take(5)->get();
}

Method 3

try this

$products = Product::latest()->take(2)->with('categories')->get();


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x