Introduction

When handling a database-driven application, it is necessary to extract data manually or automatically at the code level if an error occurs during inserting or updating. We’ll go over how to use Laravel ORM delete() to address this issue in this blog post.

Description

Eloquent ORM from Laravel offers a clear and simple syntax that makes database interactions easier. Among the most important functions you’ll utilise is delete(), which offers a simple means of eliminating entries from your database.

Example

Here’s how you can use the delete() method:
– Deleting record through model instance
When you have an instance of an Eloquent model, calling delete() will delete the corresponding record from the database. Here’s a quick example:

$getrecord = ImageGallery::find(1); // find the record and delete it
$getrecord->delete();

– Deleting record via query builder
You can also use delete() with Eloquent’s query builder to delete records that match certain criteria. For instance:

ImageGallery::where('file_index',$postdata['file_index'])->delete(); 

Alternatively, you can use a shorter approach if you know the record’s primary key:

ImageGallery::destroy(2); // Directly deletes user with ID 2

The destroy() method allows you to delete records by their primary key(s) without retrieving them first.

It also allows you to pass array of primary key(s) to delete records

ImageGallery::destroy([1,2,3]); // Deletes users with IDs 1, 2, and 3

Additionally, Laravel allows for soft deletes, which let you maintain records in the database but designate them as removed. Use the SoftDeletes trait in your model to enable soft deletes:

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class ImageGallery extends Model
{
    use SoftDeletes;

    protected $dates = ['deleted_at'];
}

Calling delete() won’t truly remove the record from the database when using soft deletes. Rather, it sets a deleted_at timestamp, which you can use to exclude records that have been “deleted”:

You can learn more about delete() in-depth details by clicking the link below.
Laravel Eloquent Deleting Models

Support On Demand!

Laravel