laravel7でPostのユーザ毎の既読管理
1, Read(既読)管理テーブルを作る。レコードが存在したら既読
| 
					 1 2 3 4 5 6  | 
						Schema::create('reads', function (Blueprint $table) {     $table->id();     $table->unsignedBigInteger('post_id')->comment('投稿記事');     $table->unsignedBigInteger('user_id')->comment('このユーザーの未読・既読');     $table->timestamps(); });  | 
					
2, POST記事を見たら、既読レコードを作る
| 
					 1 2 3 4 5 6 7 8  | 
						public function show(Post $post) {     // 既読フラグON     read::updateOrCreate(         ['post_id' => $post->id, 'user_id' => Auth::id()]     );             return view('post.show', compact('post')); }  | 
					
3, POSTモデルでリレーションを定義。
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15  | 
						namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Auth; class Post extends Model {     protected $guarded = ['id'];     // 既読フラグ     function Read()     {         return $this->belongsToMany('App\User', 'reads', 'post_id', 'user_id')->where('user_id', Auth::id());     }     }  | 
					
4, 表示をリレーションで出し分け
| 
					 1 2 3 4 5 6 7 8 9 10  | 
						public function index() {     // 既読フラグがない投稿を取得     $not_read_posts = Post::doesntHave('Read')->orderby("created_at", 'desc')->get();     // 既読フラグがあり投稿を取得     $read_posts = Post::has('Read')->orderby("created_at", 'desc')->get();     return view('home', compact('not_read_posts', 'read_posts')); }  |