How do you do soft deletes?
How do you do soft deletes?
To implement soft deletes in Laravel, follow these steps:
First, you need to add a deleted_at column to the table you want to use soft deletes with. This can be done by creating a migration:
php artisan make:migration add_deleted_at_to_posts_table --table=posts
In the generated migration file, add the softDeletes method to the up function and dropSoftDeletes to the down function:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddDeletedAtToPostsTable extends Migration
{
public function up()
{
Schema::table('posts', function (Blueprint $table) {
$table->softDeletes();
});
}
public function down()
{
Schema::table('posts', function (Blueprint $table) {
$table->dropSoftDeletes();
});
}
}
Run the migration to add the deleted_at column:
php artisan migrate
In your Eloquent model, you need to use the SoftDeletes trait. For example, in your Post model:
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
use SoftDeletes;
// Other model properties and methods...
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.