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.

リレーションで取得したデータをviewに表示したところ謎のエラー発生

Last updated at Posted at 2020-04-30

環境 laravel6.2

目標、リレーションしたデータをviewに表示

テーブルを作成

chat_messages
id
message
User.php
public function chatMessage()
 {
  return $this->hasMany('App\ChatMessage');
 }
UserController.php

public function index()
 {
  $users = User::all();
  $users->load('chatMessage');
 }
home.blade.php
@foreach ($users as $user)
  <p>{{ $user->chatMessage->message }}</p>
@endforeach

謎のエラー発生

Property [message] does not exist on this collection instance. 

とりあえず配列だけ表示してみる

home.blade.php
@foreach ($users as $user)
  <p>{{ $user->chatMessage }}</p>
@endforeach
// 出力結果
{"id":15,"message":"\u3059\u3054\u3044"},{"id":16,"message":"\u30b9\u30cb\u30fc\u30ab\u30fc"}

出力できたものの、なぜかメッセージが文字化けしている。

さらにforeachで回してみる

home.blade.php
@foreach ($users as $user)
  @foreach ($user->chatMessage as $chatMessage)
 {{ $chatMessage->message }}
  @endforeach
@endforeach

これなら出力できました。
ただ仕組みがわかっていないのでよければアドバイスいただけると幸いです。

0
0
2

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?