iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 25
0
自我挑戰組

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

D25 超簡易版FB - CRUD(3)

  • 分享至 

  • twitterImage
  •  

今天做的是Delete和其他使用者的貼文顯示。

因為之後要做留言,Update的部分也需要判斷是不是本人來修改的,所以先來處理使用者的部分。

修改了Create_Post Migration,新增user_id欄位。

Schema::create('posts', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('user_id');
    $table->string('content');
    $table->timestamps();
});

Refresh一次。

再來修改Controller的show方法:

public function show()
{
    $post = DB::table('posts')
                ->leftJoin('users', 'posts.user_id', '=', 'users.id')
                ->orderBy('posts.id', 'DESC')
                ->get();
    return view('home')->with('posts', $post);
}

後來發現用DB查詢我可能比較習慣,寫起來跟寫SQL差不多,一行一行看下來非常整齊。

Home View修正:

@if (isset($posts))
    @foreach($posts as $post)
    <div class="card">
        <div class="card-header">{{ $post->name }}</div>
        <div class="card-body">
            <p>{{ $post->content }}</p>
        </div>
    </div>
    @endforeach
@endif

現在畫面會看起來像這樣

再來是刪除文章的部分。

修改一下Route,因為我試著用表單欺騙但好像會出錯,所以還是回去用POST。

// web.php
Route::post('delete', 'UserController@delete');

刪除功能:

// UserController.php
public function delete(Request $request)
{
    $id = $request->input('post_id');
    $post = DB::table('posts')
                ->where('id', '=', $id)
                ->delete();
    return redirect()->route('home');
}

明天接續把只能刪除跟更新自己的貼文寫完。


上一篇
D24 超簡易版FB - CRUD(2)
下一篇
D26 超簡易版FB - CRUD(4)
系列文
來用Laravel做點什麼吧30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
weiting1224
iT邦新手 5 級 ‧ 2018-11-09 15:24:24

Lolo www/images/emoticon/emoticon01.gif

PS iT邦新手 5 級 ‧ 2018-11-09 20:26:23 檢舉

我愛Lolo跟Mikele(//▽//)
不知道能不能釣到同好(喂

我要留言

立即登入留言