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
comments_table、 users_table テーブル名がこの通りなら、リレーションできませんよね?
質問に載せる情報は正確に提示してください。
あと、どこまで正常に動いていて、どこがおかしいのかを書いてください。
修正しました。
> Controllerで変数に保持したい。
なぜでしょうか?どう言う必要があってこのような謎コードを生み出そうとしているのでしょうか?
Inertia.jsを採用しているため、bladeテンプレートエンジンが使用できないためです。
Inertia.jsを使ったとしてもその必要はないと思いますが…
> Controllerで変数に保持したい
どのような形式で変数に入れたいのかを例示してください。
Controllerで変数に保持することが目的でなく、表示させることが目的ですので、Inertia.jsでも行える場合はそちらについてご教示いただきたいと思います。
あなたの回答
tips
プレビュー