Product order

Intro: In this video, I’ll show you how to retrieve items in either ascending or descending order by a particular attribute. If we take a look at the products table we shall find a column named created_at, this holds the timestamp of inserting a particular item into the table, we shall display our products in descending order by this attribute created_at. And it is pretty simple…

1. Open the file ProductsController.php

2. Inside the index() function, replace the function all() by orderBy() , we shall pass the column name created_at as the first argument, and desc as the second argument to specify descending order. Finally call the function get(). $products=Product::orderBy('created_at','desc')->get();


namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\Product;

class ProductsController extends Controller
    //fetch products from the database
    public function index()
      return view('products')->with('products',$products);

    //Fetch a product by ID
    public function show($id)
        return view('product')->with("product",$product);

    //Add product information to the database
    public function store(Request $request){

      //validate the incoming data
        'title.required'=>'Please enter a title',
        'desc-sm.required'=>'Please enter a short description',
        'desc-full.required'=>'Please enter a full description',
        'price.required'=>'Please enter the product price',
        'price.numeric'=>'The price should be a number',
        'img.required'=>'Please upload an image',

      //upload the image
      $path = $request->file('img')->store('product_images');

      //submit data
      $product=new Product();




      return redirect('/product/'.$product->id);


3. Save the changes and reload the products list page. Notice the changes.

Leave a Reply

Your email address will not be published.