0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

投稿 新しい順に表示 laravel

Posted at

問題
SNSサイトを作ったが、
投稿が古い順に表示される。
投稿日時が新しい順にしたい。

解決
sortByDescを使う。
(メモ:sortByDescは降順sortByは昇順)

Controllerを編集
例)



class DogsController extends Controller
{
    // 投稿された記事の一覧を表示する
    public function index(Request $request)
    {
        $tags = Tag::all();
        $pref = $request->pref;
        $city = $request->city;
        $place = $request->place;
        $query = Post::query();
        if ($pref != '') {
        $query->where('pref', $pref);
        }
        if(!empty($city)) {   
        $query->where('city', 'like', '%'.$city.'%');
        }
        if ($place != '') {
        $query->where('place', 'like', '%'.$place.'%');
        }
        if ($request->tags && 0 < count($request->tags)){
        $query->whereIn('id', Post::getPostIdbyTags($request->tags));
        }
//この一文を書き換える!
        $posts = $query->get();
//下に書き換えた
        $posts = $query->get()->sortByDesc('created_at');


        return view('dogs.index', ['posts' => $posts, 'pref' => $pref, 'tags' => $tags]);
    }

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?