Only until March 18th: coupon LARAVEL12 for 40% off Yearly/Lifetime membership!

Read more here
Laravel Projects Examples

Laravel Soft-Deletes "On Steroids": Archive and Bin

This Laravel demo project is based on functionality of Google Keep:

  • It allows to Archive records
  • Or put them to Bin, which is auto-emptied after 7 days (or you can empty the bin manually)
  • From both Archive and Bin, you may restore the record

The idea is based on this YouTube video (Google Keep example starts at 6:16 min).

We tried to re-create the same scenario for a Tasks CRUD with Laravel.

For this example to work, we have to handle a few things:

  1. Display tasks in the table - Treat this like a To-Do list of Google Keep.
  2. Add archive functionality - Move tasks to the Archive.
  3. Add archive preview - Show archived tasks in a separate view.
  4. Add bin functionality via soft deletes - Move tasks to the Trash Bin.
  5. Add bin preview - Show tasks in the Trash Bin.
  6. Add Model Pruning - Delete tasks from the Trash Bin after a certain period.

Let's start by looking at our Task model:

Here, we need to add the SoftDeletes and Prable traits to the model and define scopes for prunable tasks and active/archived tasks.

app/Models/Task.php

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Prunable;
 
class Task extends Model
{
/** @use HasFactory<\Database\Factories\TaskFactory> */
use HasFactory;
use HasFactory, SoftDeletes, Prunable;
 
protected $fillable = ['name', 'description', 'user_id', 'archived_at'];
 
protected $dates = ['archived_at'];
 
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
 
public function prunable()
{
return static::onlyTrashed()
->where('deleted_at', '<=', now()->subDays(7));
}
 
public function scopeActive($query)
{
return $query->whereNull('archived_at');
}
 
public function scopeArchived($query)
{
return $query->whereNotNull('archived_at')
->whereNull('deleted_at');
}
}

Next we will build all of our controllers and Archive/Bin functionality.