軟刪除的意思就是沒有真正刪除,只是在數(shù)據(jù)庫里標(biāo)記了一下,便于隨時恢復(fù)。我們可以軟刪除用戶,讓他失去正常的權(quán)限,也可以隨時恢復(fù)正常的權(quán)限。我們可以軟刪除文章放到所謂的垃圾桶里,隨時可以再恢復(fù)。
為了講解這一教程,我做了一些準(zhǔn)備工作,創(chuàng)建了一個模型文件Post, 并且增加了 protected $guarded = [], 使得關(guān)掉了mass assignment。并且創(chuàng)建了一個migration文件,為了填充假數(shù)據(jù),里面只加了2個字段,title和body。做了一個控制器,做了一個index方法。
Post遷移代碼:
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
$table->text('body');
$table->timestamps();
});
}
1. 填充假數(shù)據(jù)
php artisan tinker
factory(\App\Post::class,20)->create();
2.控制器里的index方法
public function index()
{
$posts = Post::all();
return view('/', compact("posts"));
}
3.添加一個字段"deleted_at"到這個Post模型。
php artisan make:migration add_deleted_at_column_to_posts --table posts
我們來看看遷移文件:
public function up()
{
Schema::table('posts', function (Blueprint $table) {
//
});
}
我們把它修改成:
public function up()
{
Schema::table('posts', function (Blueprint $table) {
$table->timestamp("deleted_at")->nullable();
});
}
public function down()
{
Schema::table('posts', function (Blueprint $table) {
$table->dropColumn('deleted_at');
});
}
再執(zhí)行一下遷移文件:
php artisan migrate
這樣我們就增加了一個字段在posts表上。
4. 修改模型文件添加softdelete。
在模型文件頭部引入之后,現(xiàn)在的模型文件是這樣的:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
use SoftDeletes;
protected $guarded = [];
}
5.測試軟刪除
我們可以直接在tinker里面測試軟刪除。
php artisan tinker
假若我們想軟刪除第一個記錄,那么我們就執(zhí)行如下命令:
$post = \App\Post::where('id',1)->first();
$post->delete();
跟我們一般的刪除是一樣的,但是你如果查一下數(shù)據(jù)庫的話,就會發(fā)現(xiàn),記錄并沒有刪除,那么我們?nèi)绾尾拍懿榈竭@個記錄呢?
\App\Post::where('id',1)->withTrashed()->first();
如果我們想恢復(fù)一下,如何做呢?
\App\Post::where('id',1)->withTrashed()->first()->restore();
如果我們想真正刪除這個記錄,該如何做呢?
\App\Post::where('id',1)->withTrashed()->first()->forceDelete();