Home > Mobile >  How can I show the latest/last product products that has been added DB from my controller
How can I show the latest/last product products that has been added DB from my controller

Time:11-10

I'm making an ecommerce store and I want to show the latest record that has been added from the database using my product controller. Can anyone who's an expert at laravel kindly assist? I have not idea on how to do that.

Here's the code from my controller, that's displaying products on the landing page

public function index()
  {
  return view('/welcome')->with([
  'products' => $this->getProducts(4),
]);
}

public function getProducts(int $limit) {
Product::orderByDesc('created_at')->skip(0)->take($limit)->get();
}

After implementing this update that was recommended that was recommended and closing the 'created_at' string, I'm getting an error 'Invalid argument supplied for foreach()'. Is there anyway I can get rid of this error?

CodePudding user response:

If your product table has some datetime column then you'll have to order by that column as you want to show your latest results. So you can modify your query like below

Product::orderByDesc('created_at)->offset(0)->limit($limit)->get();

Or you can make use of the alternative skip and take method

Product::orderByDesc('created_at)->skip(0)->take($limit)->get();

If you don't have a datetime column (created_at in this case) and your Product model has auto incrementing id column then you can just do

Product::orderBy('id', 'desc')->skip(0)->take($limit)->get();

For more info please read this

  • Related