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();
<?php
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()
{
$products=Product::orderBy('created_at','desc')->get();
return view('products')->with('products',$products);
}
//Fetch a product by ID
public function show($id)
{
$product=Product::find($id);
return view('product')->with("product",$product);
}
//Add product information to the database
public function store(Request $request){
//validate the incoming data
$request->validate([
'title'=>'required',
'desc-sm'=>'required',
'desc-full'=>'required',
'price'=>'required|numeric',
'img'=>'required'
],
[
'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();
$product->title=$request->input('title');
$product->short_desc=$request->input('desc-sm');
$product->long_desc=$request->input('desc-full');
$product->price=$request->input('price');
$product->image_url=$path;
$product->user_id=Auth::id();
$product->save();
return redirect('/product/'.$product->id);
}
}
3. Save the changes and reload the products list page. Notice the changes.