Просмотр исходного кода

Lesson 15: Eloquent relationships and comments.

Frederic G. MARAND 6 лет назад
Родитель
Сommit
3db1fabaf4

+ 10 - 0
app/Comment.php

@@ -0,0 +1,10 @@
+<?php
+
+namespace App;
+
+class Comment extends Model
+{
+    public function post() {
+        return $this->belongsTo(Post::class);
+    }
+}

+ 4 - 0
app/Post.php

@@ -11,4 +11,8 @@ class Post extends Model {
    */
   protected $fillable = ['body', 'title'];
 
+  public function comments()
+  {
+      return $this->hasMany(Comment::class);
+  }
 }

+ 33 - 0
database/migrations/2017_09_02_190346_create_comments_table.php

@@ -0,0 +1,33 @@
+<?php
+
+use Illuminate\Support\Facades\Schema;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Database\Migrations\Migration;
+
+class CreateCommentsTable extends Migration
+{
+    /**
+     * Run the migrations.
+     *
+     * @return void
+     */
+    public function up()
+    {
+        Schema::create('comments', function (Blueprint $table) {
+            $table->increments('id');
+            $table->integer('post_id');
+            $table->string('body');
+            $table->timestamps();
+        });
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        Schema::dropIfExists('comments');
+    }
+}

+ 21 - 1
resources/views/posts/show.blade.php

@@ -2,6 +2,26 @@
 
 @section('content')
     <div class="col-sm-8 blog-main">
-        @include('posts.post')
+        <h1>{{ $post->title }}</h1>
+        <p class="blog-post-meta">
+            {{ $post->created_at->toFormattedDateString() }}
+            by <a href="#">Mark</a>
+        </p>
+
+        {{ $post->body }}
+        @if (count($post->comments))
+        <hr />
+        <div class="comments">
+            <ul class="list-group">
+                @foreach($post->comments as $comment)
+                <li class="list-group-item">
+                    <strong>{{ $comment->created_at->diffForHumans() }}</strong>
+                    :&nbsp;
+                    {{ $comment->body }}
+                </li>
+                @endforeach
+            </ul>
+        </div>
+        @endif
     </div>
 @endsection