iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 28
1
自我挑戰組

來用Laravel做點什麼吧系列 第 28

D28 超簡易版FB - 留言(2)

接續昨天的留言。

// CommentController.php

public function create(Request $request)
{
    $comment = new Comment;
    $comment->user_id = Auth::user()->id;
    $comment->post_id = $request->input('post_id');
    $comment->message = $request->input('message');
    $comment->save();

    return redirect()->route('home');
}

public function delete($id)
{
    $post = DB::table('comments')
                ->where('comment_id', '=', $id)
                ->delete();

    return redirect()->route('home');
}

重點在View這邊,我把留言的部分另外切一個子視圖comment.blade.php出來。

// home.blade.php
<div>@include('comment', ['comments' => $comments])</div>

Home多增加一行引入子視圖。

<div>
    <form method="POST" action="{{ route('c_create') }}">
        @csrf
        <input type="hidden" name="post_id" value="{{ $post->post_id }}">
        <input type="text" name="message">
        <button type="submit" class="btn btn-primary">Comment</button>
    </form>
    @foreach($comments as $comment)
    @if($comment->post_id === $post->post_id)
    <div>
        <p>{{ $comment->name }} : {{ $comment->message }}</p>
        @if(($comment->user_id) === (Auth::user()->id))
            <form action="{{ route('c_destroy', $comment->comment_id) }}" method="POST">
                @csrf
                <button>Delete</button>
            </form>
        @endif
    </div>
    @endif
    @endforeach
</div>

Create的部分跟貼文一樣,只是另外用一個hidden記錄這則留言是給哪一則貼文的。

子視圖會繼承父視圖攜帶的資料,所以在comment.blade.php裡面也可以使用$post,比較$comment$postpost_id欄位,就能只顯示該貼文的留言。

Delete功能比照貼文,只有使用者本人可以刪除自己的留言。


上一篇
D27 超簡易版FB - 留言(1)
下一篇
D29 超簡易版FB - 搜尋
系列文
來用Laravel做點什麼吧30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
eric19740521
iT邦新手 1 級 ‧ 2020-02-25 17:23:20

請問有商品上架的說明嗎???謝謝

我要留言

立即登入留言