Câu hỏi phỏng vấn Laravel
Câu hỏi

How do you do soft deletes?

Câu trả lời

To implement soft deletes in Laravel, follow these steps:

1. Create a Migration

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:

bash Copy
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:

php Copy
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:

bash Copy
php artisan migrate

2. Use the SoftDeletes Trait

In your Eloquent model, you need to use the SoftDeletes trait. For example, in your Post model:

php Copy
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model
{
    use SoftDeletes;

    // Other model properties and methods...
}

3. Soft Deleting Records

You can now soft delete records by calling the delete method on an Eloquent model instance:

php Copy
$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.

4. Querying Soft Deleted Records

To retrieve soft-deleted records, you can use the withTrashed method. For example, to retrieve all soft-deleted posts:

php Copy
$softDeletedPosts = Post::onlyTrashed()->get();

To include both soft-deleted and non-deleted records in your query, use withTrashed:

php Copy
$allPosts = Post::withTrashed()->get();
```...
middle

middle

Gợi ý câu hỏi phỏng vấn

senior

Why do we need Traits in Laravel?

middle

What is Closure in Laravel?

middle

What is Laravel Passport?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào