ユーザーと投稿内容を紐付けて、投稿したものにユーザー名を表示させたいと思っています。
ユーザーは複数のツイートを持っている
ツイートはひとつのuser_idを持っているというリレーションを組みました。しかし下記のコードではオブジェクトのプロパティーがないというエラーが出てしまいました。
dumpで確認したところ、ユーザーもユーザーIDもnullになっていました。
オーソドックスな書き方をしたと思うのですが・・・
ここが原因なのでは?というところが在りましたらご指摘いただきたいです
エラー
http://localhost:8000/ (2/2) ErrorException Trying to get property of non-object (View: C:\xampp\htdocs\Twitter_crone\twitter_clone\twc\resources\views\tweets\index.blade.php)
ビュー
@foreach($tweets as $tweet) <p class="lead">{{ $tweet->created_at->toFormattedDateString() }}</p> <p class="lead">{{ $tweet->user->username }}</p> <a href="/tweets/{{ $tweet->id }}"> <p class="lead">{{ $tweet->body }}</p> </a> @endforeach
tweet migrate
public function up() { Schema::create('tweets', function (Blueprint $table) { $table->increments('id'); $table->text('body'); $table->integer('user_id')->nullable(); $table->timestamps(); }); }
Tweet Model
public function user() { return $this->belongsTo(User::class); }
User Model
public function tweets() { return $this->hasMany(Tweet::class); }
dumpしてみた
Collection {#210 ▼ #items: array:3 [▼ 0 => Tweet {#217 ▼ #guarded: array:2 [▼ 0 => "id" 1 => "created_at" ] #connection: "mysql" #table: null #primaryKey: "id" #keyType: "int" +incrementing: true #with: [] #withCount: [] #perPage: 15 +exists: true +wasRecentlyCreated: false #attributes: array:5 [▼ "id" => 5 "body" => "twasdsfgfjghrty" "user_id" => null "created_at" => "2017-07-07 09:56:47" "updated_at" => "2017-07-07 09:56:47" ] #original: array:5 [▼ "id" => 5 "body" => "twasdsfgfjghrty" "user_id" => null "created_at" => "2017-07-07 09:56:47" "updated_at" => "2017-07-07 09:56:47" ] #casts: [] #dates: [] #dateFormat: null #appends: [] #events: [] #observables: [] #relations: array:1 [▼ "user" => null ] #touches: [] +timestamps: true #hidden: [] #visible: [] #fillable: [] } 1 => Tweet {#218 ▶} 2 => Tweet {#219 ▶} ] }
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/07/11 05:20 編集