CRUD (Create, Read, Update, and Delete) operations with soft deletes in Laravel


  • Create a migration to add deleted_at column to the table:


php artisan make:migration add_deleted_at_to_table_name --table=table_name
public function up()
{
    Schema::table('table_name', function (Blueprint $table) {
        $table->softDeletes();
    });
}

  • Add SoftDeletes trait and deleted_at column to the model:

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

class YourModel extends Model
{
    use SoftDeletes;

    protected $dates = ['deleted_at'];
}

  • Create a controller for the resource:

use App\Models\YourModel;
use Illuminate\Http\Request;

class YourModelController extends Controller
{
    public function index()
    {
        $records = YourModel::all();
        return view('your_view_name.index', compact('records'));
    }

    public function create()
    {
        return view('your_view_name.create');
    }

    public function store(Request $request)
    {
        $record = new YourModel;
        $record->fill($request->all());
        $record->save();
        return redirect()->route('your_route_name.index');
    }

    public function show($id)
    {
        $record = YourModel::withTrashed()->find($id);
        return view('your_view_name.show', compact('record'));
    }

    public function edit($id)
    {
        $record = YourModel::withTrashed()->find($id);
        return view('your_view_name.edit', compact('record'));
    }

    public function update(Request $request, $id)
    {
        $record = YourModel::withTrashed()->find($id);
        $record->fill($request->all());
        $record->save();
        return redirect()->route('your_route_name.index');
    }

    public function destroy($id)
    {
        $record = YourModel::withTrashed()->find($id);
        $record->forceDelete();
        return redirect()->route('your_route_name.index');
    }
}

  • Define the routes for the controller in the routes/web.php file:

Route::resource('your_route_name', YourModelController::class);
Now you can access the CRUD operations for the resource by going to the appropriate URLs. For example, to create a new record, go to your_base_url/your_route_name/create. To edit an existing record, go to your_base_url/your_route_name/{id}/edit. And so on. Note that the forceDelete() method is used in the destroy() method to permanently delete the record. If you want to soft delete the record, use the delete() method instead.

Post a Comment

0 Comments