Laravelでコメントした人の情報をuser_idを元にユーザ名を表示させたい。
また、この時Bladeで表示させるのではなく、Controllerで変数に保持したい。
テーブル名: comments
php
1 $table->id(); 2 $table->unsignedBigInteger('post_id'); 3 $table->unsignedBigInteger('user_id'); 4 $table->foreign('user_id')->references('id')->on('users'); 5 $table->foreign('post_id')->references('id')->on('posts'); 6 $table->text('content'); 7 $table->timestamps();
テーブル名: users
php
1 $table->id(); 2 $table->string('name'); 3 $table->string('email')->unique(); 4 $table->string('password'); 5 $table->timestamps();
comment model
php
1class Comment extends Model 2{ 3 use HasFactory; 4 5 protected $fillable = [ 6 'content', 7 ]; 8 9 public function user(){ 10 return $this->belongsTo(User::class); 11 } 12 13 public function posts(){ 14 return $this->belongsTo(Post::class); 15 } 16}
user model
public function comments(){ return $this->hasMany(Comment::class, 'user_id', 'id'); }
###試したこと
Controller
php
1$post = Post::find($id); 2$comments = $post->comment; 3$comments_user = $post->comment->user->name; //これや 4$comments_user = $comments->user->name; //これを試した
$comments = $post->comment;
までは取得することができ、該当するデータpost_id
, user_id
, content
を確認することができた。
発生エラー
Property [user] does not exist on this collection instance.
環境
Laravel 8.x
あなたの回答
tips
プレビュー