5
1

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初心者】投稿者かどうかによって表示を変える

Posted at

Laravel初学者です。
オリジナルアプリを作成しているのでその過程を記事にしています。

理解が曖昧なところも多いため、ご指摘等ありましたらご連絡いただければ幸いです。

今回は詳細画面にて投稿者のみ編集と削除のボタンが表示されるという実装について備忘録のため残します。

環境

Version
PHP 7.4.14
Laravel 8.24.0
mysql 8.0.23
docker 20.10.2
docker-compose 1.27.4

コントローラー

app/Http/Controllers/GameController.php

$user_id = Auth::id();

私の場合はshowアクションで表示する画面で投稿者かどうかの条件分岐を入れたかったのでshowアクションに上記の記述をしました。

ビュー

@if ($user_id == $game->user_id)
  <div class="mb-4 text-center" style="margin-top:10px">
    <a href="{{ route('game.edit', $game->id) }}" class="btn btn-primary">
      編集する
    </a>
    <form
      style="display: inline-block;"
      method="POST"
      action="{{ route('game.destroy', $game->id) }}"
     >
     @csrf
     @method('DELETE')
     <button class="btn btn-danger">削除する</button>
     </form>
   </div>
@endif

上記のように

@if ($user_id == $game->user_id)

で現在のログインユーザーのidと投稿($game)のuser_idが一致する場合は編集と削除の表示が出るように条件分岐しました。

以上です。

5
1
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
5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?