実現したいこと
ブログサイトの投稿を新着順にしたい
前提
PHP Laravelでブログサイトを作っています。
投稿を新着順にしたいのですがうまく新着順にならない。
該当のソースコード
PostController.php
php
1<?php 2 3namespace App\Http\Controllers; 4 5use Illuminate\Http\Request; 6use App\Post; 7use App\Http\Requests\PostRequest; 8use App\Http\Requests\PostImageRequest; 9use App\User; 10 11class PostController extends Controller 12{ 13 // 投稿一覧 14 public function index(){ 15 $user = \Auth::user(); 16 $posts = \Auth::user()->posts()->latest()->get(); 17 return view('posts.index', [ 18 'title' => '投稿一覧', 19 'user' => $user, 20 ]); 21 } 22 23 // 新規投稿フォーム 24 public function create() 25 { 26 return view('posts.create', [ 27 'title' => '新規投稿', 28 ]); 29 } 30 31 // 投稿追加処理 32 public function store(PostRequest $request){ 33 Post::create([ 34 'user_id' => \Auth::user()->id, 35 'comment' => $request->comment, 36 ]); 37 session()->flash('success', '投稿を追加しました'); 38 return redirect()->route('posts.index'); 39 } 40 41 // 投稿詳細 42 public function show($id) 43 { 44 return view('posts.show', [ 45 'title' => '投稿詳細', 46 ]); 47 } 48 49 // 投稿編集フォーム 50 public function edit($id) 51 { 52 // ルーティングパラメータで渡されたidを利用してインスタンスを取得 53 $post = Post::find($id); 54 return view('posts.edit', [ 55 'title' => '投稿編集', 56 'post' => $post, 57 ]); 58 } 59 60 // 投稿更新処理 61 public function update($id, PostRequest $request) 62 { 63 $post = Post::find($id); 64 $post->update($request->only(['comment'])); 65 session()->flash('success', '投稿を編集しました'); 66 return redirect()->route('posts.index'); 67 } 68 69 // 投稿削除処理 70 public function destroy($id) 71 { 72 $post = Post::find($id); 73 74 $post->delete(); 75 session()->flash('success', '投稿を削除しました'); 76 return redirect()->route('posts.index'); 77 } 78 79 public function __construct() 80 { 81 $this->middleware('auth'); 82 } 83}
index.blade.php
php
1@extends('layouts.logged_in') 2 3@section('title', $title) 4 5@section('content') 6 <h1>{{ $title }}</h1> 7 <ul> 8 @forelse($user->posts as $post) 9 <li> 10 {{ $post->user->name }}: 11 {!! nl2br($post->comment) !!}<br> 12 ({{ $post->created_at }}) 13 @if($user->isEditable($post)) 14 [<a href="{{ route('posts.edit', $post) }}">編集</a>] 15 @endif 16 <form action="{{ url('posts/'.$post->id) }}" method="post"> 17 @csrf 18 @method('delete') 19 <button type="submit">削除</button> 20 </form> 21 </li> 22 @empty 23 <p>投稿がありません。</p> 24 @endforelse 25 </ul> 26@endsection
試したこと
Controllerに$posts = \Auth::user()->posts()->latest()->get();を書いたのですが、新着順にならなかった。
補足情報(FW/ツールのバージョンなど)
過去の投稿でログイン機能を自作していたのですが、それはやめてlaravelの最初からあるログイン機能を使用しています。

回答1件
あなたの回答
tips
プレビュー