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.

コメント機能 laravel

Last updated at Posted at 2021-10-25

マイグレーションファイルの作成

$ php artisan make:migration create_comments_table --create=comments
comments_table.php
    public function up()
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('article_id');
            $table->unsignedInteger('user_id');
            $table->text('content');
            $table->foreign('article_id')->references('id')->on('articles')->onDelete('cascade');
            $table->foreign('user_id')->references('id')->on('users');
            $table->timestamps();
        });
    }

説明

符号なしINTカラム
コメントを postに紐付ける

$table->unsignedInteger('article_id');

外部キー制約
foreign('article_id')
references('id')
どこの→idarticles

onDelete()
cascade→articleが削除された時に関連するコメントも一気に削除

モデル作成

$ php artisan make:model Comment
Comment.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    protected $fillable = ['content'];

    public function article()
    {
        return $this->belongsTo('App\Article', 'article_id');
    }

    public function user()
    {
        return $this->BelongsTo('App\User', 'user_id');
    }
}
Article.php
//追加
    public function comments() {
        return $this->hasMany('App\Comment');
    }

マイグレーション

$ php artisan migrate

シーダーファイルの作成

$ php artisan make:seeder CommentsTableSeeder
CommentsTableSeeder.php
public function run()
    {
        for ($i = 0; $i < 30; $i++) {
            $faker = Faker\Factory::create();

            $param = [
                'content' => $faker->paragraph(),
                'created_at' => Carbon::today(),
                'updated_at' => Carbon::today(),
                'article_id' => $faker->numberBetween(1, 10),
                'user_id' => $faker->numberBetween(1, 10),
            ];

            DB::table('comments')->insert($param);
        }
    }

シーダーを実行する順番を追加

DetabaseSeeder.php
//最後に追加
$this->call('CommentsTableSeeder');

シーダーの実行

$ php artisan db:seed

ルート

web.php
Route::resource('comment', 'CommentsController', ['only' => ['']]);

コントローラー

ファイルの作成

$ php artisan make:controller CommentsController

view

detail.php
    <div class="card w-50 mx-auto m-5">
        <div class="card-body">
            <div class="pt-2">
                <p class="text-muted font-weight-bold h4 border-bottom border-secondary pb-3">コメント</p>
            </div>
            @if($articles->comments->isNotEmpty())
                @foreach ($articles->comments as $comment)
                    <div class="border-bottom border-secondary pt-2">
                        <p class="text-muted mx-3 pt-1">{{ $comment->user->name }}
                            {{ $comment->created_at->format('Y年n月j日') }}に投稿</p>
                        <p class="text-muted mx-3">{!! nl2br(e($comment->content)) !!}</p>
                    </div>
                @endforeach
                {{--            TODO:コメント入力欄コメントボタンの設置--}}
            @else
                <p class="text-center pt-2">コメントはまだ投稿されていません</p>
            @endif
        </div>
    </div>
    </div>

0
0
0

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?