LoginSignup
1
2

More than 3 years have passed since last update.

ユーザーの論理削除(ソフトデリート)の実装手順

Last updated at Posted at 2020-02-29

はじめに

論理削除(ソフトデリート)の実装手順をメモします。

  • バージョン php: 7.2 laravel: 5.8
  • Authは実装済みでユーザーも登録済みであること

usersテーブルにdelete_atカラムを追加

下記コマンドでカラム追加用のマイグレーションファイルを作成する。

$ php artisan make:migration add_column_softDeletes_users_table --table=users

マイグレーションファイルを下記のように編集する。
up関数とdown関数に下記を追記する。

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddColumnSoftDeletesUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            //下記を追加
            $table->softDeletes();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            //下記を追加
            $table->dropColumn('deleted_at');
        });
    }
}

up関数に
$table->softDeletes();
を追加すると、deleted_atカラムをusersテーブルに追加できます。
このdeleted_atカラムにおいて論理削除のON/OFFを切り替えます。

下記コマンドにてup関数を実行します。

$ php artisan migrate

usersテーブルのカラム構成を確認する。
確認方法は下記投稿に書いてあります。
LaravelのMYSQLのコマンド一覧【随時更新予定】

+-------------------+---------------------+------+-----+---------+----------------+
| Field             | Type                | Null | Key | Default | Extra          |
+-------------------+---------------------+------+-----+---------+----------------+
| id                | bigint(20) unsigned | NO   | PRI | NULL    | auto_increment |
| name              | varchar(255)        | NO   |     | NULL    |                |
| email             | varchar(191)        | NO   | UNI | NULL    |                |
| email_verified_at | timestamp           | YES  |     | NULL    |                |
| password          | varchar(255)        | NO   |     | NULL    |                |
| remember_token    | varchar(100)        | YES  |     | NULL    |                |
| created_at        | timestamp           | YES  |     | NULL    |                |
| updated_at        | timestamp           | YES  |     | NULL    |                |
| deleted_at        | timestamp           | YES  |     | NULL    |                |
+-------------------+---------------------+------+-----+---------+----------------+

Fieldの一番下に「deleted_at」が確認できます。

Userモデルの編集

ModelクラスとSoftDeletesクラスを利用できるように設定します。

User.php
<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

//追記
use Illuminate\Database\Eloquent\Model;
//追記
use Illuminate\Database\Eloquent\SoftDeletes;


class User extends Authenticatable
{
    use Notifiable;

    //追記
    use SoftDeletes;


    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

Controllerの実装

AuthクラスとUserクラスを利用できるように設定してsoftdeleteアクションを追加します。
リダイレクト先にURL(news/index)を設定します。

UserController.php
<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
//追記
use Illuminate\Support\Facades\Auth;
//追記
use App\User;

class UserController extends Controller
{
    //追記
    public function softdelete()
    {
        User::find(Auth::id())->delete();
        //リダイレクト先の設定
        return redirect('news/index');
    }
}

Viewの実装

論理削除ボタンを作ります。

user/index.blade.php
<a href="{{ action('Admin\UserController@softdelete') }}">
    <button>論理削除</button>
</a>

ボタンは下記になります。
image.png

Routingの設定

web.php
<?php
namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
//追記
use Illuminate\Support\Facades\Auth;
//追記
use App\User;

class UserController extends Controller
{

Route::group(['middleware' => 'auth:user'], function()
{ 
    //追記
    Route::get('user/softdelete', 'Admin\UserController@softdelete');
});
}

これで実装は完了です。
論理削除ボタンを押せばログイン中のユーザーが論理削除されます。
usersテーブル内のデータを確認すればdeleted_atカラムがNULLから日付に変更されているはずです。
例えば下記テーブルで見ると、name2とname3が論理削除されています。

mysql> select id, name, deleted_at from users;                                                                                                                                                                                                  
+----+----------+---------------------+
| id | name  | deleted_at          |
+----+----------+---------------------+
|  1 | name1 | NULL                |
|  2 | name2 | 2020-02-29 02:01:49 |
|  3 | name3 | 2020-02-29 01:56:39 |
+----+----------+---------------------+

参考

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