简体   繁体   中英

Why is the orderBy method in my PHP code not working?

I wrote this PHP code in Laravel 5 and orderBy won't work.

Route::get('/products',function (){$products= DB::table('products')->get();
return view('products.index',compact('products'));});

Route::get('/products/{id}',function ($id){$product= DB::table('products')->find($id);
        return view('products.show',compact('product'));});

and index.blade.php code is

 <div><a href={{"/products/".$product->id}}>{{$product->name}}</a></div>

and show.blade.php code is:

 <h1>{{$product->name}}</h1>
 <p> {{$product->description}}</p>

When you use find() it will return only 1 registry. So, order by has no effect.

If the $id is present in more than 1 row, then you should use where and get()

$product= DB::table('products')->where('id','=',$id)->orderBy('name','desc')->get();

So, if you add order by, it should work:

Route::get('/products',function (){
    $products= DB::table('products')->orderBy('name','desc')->get();
    return view('products.index',compact('products'));
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM