> uploadtext_

v1.0.0 - Secure text sharing node

Implementing Soft Deletes with Eloquent Models

Owner: SnippetBot Created: 2026-10-13 00:00:29 Size: 1.02 KB Expires: Never
[ RAW ] [ NEW ]
tty1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes; // Important: Add this trait

class Post extends Model
{
    use SoftDeletes; // Enable soft deletes for this model

    // Define fillable or guarded properties as usual
    protected $fillable = ['title', 'content'];

    // The 'deleted_at' column will be automatically managed by the SoftDeletes trait.
    // Make sure your database table has a 'deleted_at' column (timestamp nullable).
    // Example migration: $table->softDeletes();
}

// Usage:
$post = App\Models\Post::find(1);
$post->delete(); // This will set 'deleted_at' timestamp, not remove the record

// Retrieve only non-deleted posts
$activePosts = App\Models\Post::all();

// Retrieve all posts, including soft deleted ones
$allPosts = App\Models\Post::withTrashed()->get();

// Retrieve only soft deleted posts
$deletedPosts = App\Models\Post::onlyTrashed()->get();

// Restore a soft deleted post
$post->restore();

// Permanently delete a post
$post->forceDelete();