Support Online
Skip to main content

How to Delete Database Records with Laravel Eloquent?

Deleting records from the database is quite easy using Laravel's Eloquent ORM. In this guide, you'll learn how to delete database records using Eloquent's delete method, specifically how to reassign related items when deleting lists. You'll also discover how you can automate this process with Laravel Artisan commands.

What Will You Learn in This Guide?

You will learn the basic commands to be used to delete database records in Eloquent ORM, and you will see how to move related items to another list when deleting a list. You'll also discover how you can automate this process with Laravel Artisan commands.

1. Creating a New Artisan Command

First, let's automate the function of deleting lists via an Artisan Command. If you are using a containerized environment, you must run the command within the app service.

Starting the Script:

docker-compose exec app php artisan make:command ListDelete

Creates a new script in Laravel's app/Console/Commands/ListDelete.php directory.


2. Implementing the ListDelete Command

Let's open the ListDelete.php file we created and add the logic for deleting and reassigning associated records.

Defining the Command Signature and Description:

The variable $signature determines the command name and the mandatory parameter (list_slug).

Writing the handle() Method:

The handle() method contains the main logic that will be triggered when the command runs.

File Content `(app/Console/Commands/ListDelete.php)````:

The existing template code should be replaced with the following content:


<?php

namespace App\Console\Commands;

use App\Models\Link;
use App\Models\LinkList;
use Illuminate\Console\Command;

class ListDelete extends Command
{
protected $signature = 'list:delete &#123;list_slug&#125;';
protected $description = 'Veritabanından listeleri siler.';

public function __construct()
{
parent::__construct();
}

public function handle()
{
$list_slug = $this->argument('list_slug');
$list = LinkList::firstWhere('slug', $list_slug);

if ($list === null) {
$this->error("Geçersiz veya bulunamayan liste.");
return 1;
}

if ($this->confirm("'$list->title' listesi silinsin mi? Tüm ilişkili linkler varsayılan listeye atanacak.")) {
$default_list = LinkList::firstWhere('slug', 'default');
if (!$default_list) {
$default_list = new LinkList();
$default_list->title = 'default';
$default_list->slug = 'default';
$default_list->save();
}

$this->info("Linkler varsayılan listeye atanıyor...");

// 🔑 Tüm ilişkili Link'leri bulur ve ID'lerini varsayılana günceller.
Link::where('link_list_id', $list->id)->update(['link_list_id' => $default_list->id]);

// 🔑 Listeyi veritabanından siler.
$list->delete();
$this->info("Liste başarıyla silindi.");
}

return 0;
}
}

This code finds the list, asks the user for confirmation, and then updates the associated records and deletes the parent record.


3. Testing Deletion

Let's test it by running the command we created.

Let's first see the existing lists and links in the database.


docker-compose exec app php artisan link:show

This command shows which lists existing links belong to.

Running the Delete List Command:

For example, let's delete the list with the slug social.


docker-compose exec app php artisan list:delete social
Confirmation Prompt:

Confirm the operation by typing y in the confirmation prompt that appears on the command line and pressing ENTER.


Confirm deleting the list 'social'? Tüm ilişkili linkler varsayılan listeye atanacak. (yes/no) [no]:
> y

Reassigning links to default list...
Liste başarıyla silindi.
Verifying the Result:

By checking the links again, you can see that the links in the social list have been moved to the default list.


docker-compose exec app php artisan link:show

Shows the new list of links after deletion. You will now see the default list instead of the social list.


Frequently Asked Questions (FAQ)

  1. How many ways are there to deregister in Eloquent?

There are two basic ways: Delete via Model instance ($kayit->delete()) and Bulk delete via Query (Model::where('sutun', $deger)->delete()). The first triggers events, the second is faster but does not trigger events.

  1. Why did we bulk update with the update() method?

If we deleted the direct list, all associated links would remain orphaned. To avoid this situation, we securely assigned the child records to another parent record with a bulk SQL query before deleting the parent record.

  1. What does LinkList::firstWhere('slug', 'default') do?

This expression finds the first record in the LinkList model whose slug column has a value of 'default'. This is a critical Eloquent query method to obtain the ID of the list to be deleted before doing $list->delete() in PHP.

  1. What is $this->confirm() used for?

This is a method specific to Artisan Commands. It allows obtaining written consent from the user before performing a transaction. This creates a layer of security for irreversible operations (such as deletion).


Result

In this guide, you learned how to delete lists in the database with Laravel, how to move related items to another list, and how to automate this process with Artisan commands. Now you can easily perform database management operations by using these commands in your Laravel projects. You can speed up your development processes by creating special containers for your Laravel application on the GenixNode platform.