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...
}
You can now soft delete records by calling the delete
method on an Eloquent model instance:
$post = Post::find($id);
$post->delete();
This will set the deleted_at
timestamp to the current date and time, marking the record as "deleted" without actually removing it from the database.
To retrieve soft-deleted records, you can use the withTrashed
method. For example, to retrieve all soft-deleted posts:
$softDeletedPosts = Post::onlyTrashed()->get();
To include both soft-deleted and non-deleted records in your query, use withTrashed
:
$allPosts = Post::withTrashed()->get();
```...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào