1
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】Auth機能を使って、ユーザーを識別する方法

Posted at

概要

Authの機能でユーザーを識別する方法を、例を使って紹介します。

例として、掲示板機能で自分が作成した記事にだけ、更新ボタンや削除ボタンをつけたいとします。

その場合、ログインしているユーザーと記事に紐づいているユーザーIDを一致させる必要があるかと思います。

そこで、Auth機能を使ってあげるといいかと思います。

下記に実装した方法を記載します。

使用環境

Laravel 6.2
MySQL 8.0

前提条件

・投稿テーブルのカラムに外部キーが設定してある。

実装

例えば、Viewを出力するControllerがあります。
こんなふうなものです。

Controller
public function index()
{
    $hoges = DB::all();
    return view('hoge.index',compact('hoges'));
  
}

出力されるファイルは、以下で中身を表示するのはだいたいこんなふうになるでしょうか。

view
@foreach($hoges as $hoge)
{{ $hoge->name }}
{{ $hoge->body }} 

@endforeach

ここで自身の投稿にだけ更新ボタンや削除ボタンなどを実装するものは以下です。

view
@foreach($hoges as $hoge)
{{ $hoge->name }}
{{ $hoge->body }} 

@if(Auth:id() === $hoge->user_id)
<button type="button">
削除
</button>
<button type="button">
更新
</button>
@endforeach

こんな感じで実装が簡単にできます。

ぜひお試しください。

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