Support Online
Skip to main content

Database Management Guide with Laravel Artisan Commands

What will you learn in this guide?
You will learn step by step how to manage your application's database (DB) records using Laravel Artisan commands. You will practically see how to add new records (link: new), list existing records (link: list) and delete them when necessary (link: delete) via the server console. This method is an ideal solution for background tasks and prototyping.

1. Creating a New Connection Add Command (link:new)

Artisan is Laravel's command line tool and speeds up the development process. First, let's create the command that will add a new record to the database.

Creating the Script

Use the make:command helper to create a new Artisan command:

docker-compose exec app php artisan make:command LinkNew

This command creates the file app/Console/Commands/LinkNew.php.

Defining Command Signature and Logic

Open the created LinkNew.php file. Place the signature, which is the executable name of the command ($signature), and the main business logic in the method handle():


nano app/Console/Commands/LinkNew.php

Replace the file with the code below. This code; It asks for the URL, checks its validity, asks for clarification and saves it in the database for confirmation.


// app/Console/Commands/LinkNew.php
<?php

namespace App\Console\Commands;

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

class LinkNew extends Command
{
protected $signature = 'link:new';
protected $description = 'Yeni bir Baglanti olusturur';

public function handle()
{
$url = $this->ask('Baglanti URL:');

// URL dogrulama
if (!filter_var($url, FILTER_VALIDATE_URL)) {
$this->error("Gecersiz URL. Cikiliyor...");
return 1; // Hata kodu ile cikis
}

$description = $this->ask('Baglanti Aciklamasi:');

$this->info("Yeni Baglanti:");
$this->info($url . ' - ' . $description);

if ($this->confirm('Bilgiler dogru mu?')) {
$link = new Link();
$link->url = $url;
$link->description = $description;
$link->save();

$this->info("Kaydedildi.");
}

return 0; // Basarili cikis
}
}
Running the Command

Test the command you created by running it from the terminal. We can use the example domain name example.com:


docker-compose exec app php artisan link:new

This command starts the process of adding a new connection record.


Now, let's create our second command that will list all connections in the database.

Creating the Script

Create a new file for the listing command:


docker-compose exec app php artisan make:command LinkList

This command creates the file app/Console/Commands/LinkList.php.

Showing All Records in Table Form

Open the LinkList.php file and pull all records with Eloquent in the handle() method and print them to the console using the table:


nano app/Console/Commands/LinkList.php

Replace the file with the following code:


// app/Console/Commands/LinkList.php
<?php

namespace App\Console\Commands;

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

class LinkList extends Command
{
protected $signature = 'link:list';
protected $description = 'Veritabanina kaydedilmis baglantilari listeler';

public function handle()
{
$headers = ['id', 'url', 'aciklama'];
$links = Link::all(['id', 'url', 'description'])->toArray();

$this->table($headers, $links);

return 0;
}
}
Running the Command

To see your records in tabular form, run the command:


docker-compose exec app php artisan link:list

Finally, let's prepare the command that deletes a record according to the given identification (ID) number.

Creating the Script

Create a new file for the delete command:


docker-compose exec app php artisan make:command LinkDelete

This command creates the file app/Console/Commands/LinkDelete.php.

Defining Argument and Delete Logic

For this command to work, the user must receive the ID of the record to be deleted as an argument. Let's define this argument in the signature: link:delete &#123;link_id&#125;.


nano app/Console/Commands/LinkDelete.php

Replace the file with the following code:


// app/Console/Commands/LinkDelete.php
<?php

namespace App\Console\Commands;

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

class LinkDelete extends Command
{
protected $signature = 'link:delete &#123;link_id&#125;';
protected $description = 'Veritabanindan bir baglantiyi siler.';

public function handle()
{
$link_id = $this->argument('link_id');
$link = Link::find($link_id);

if ($link === null) {
$this->error("Gecersiz veya mevcut olmayan baglanti ID'si.");
return 1;
}

if ($this->confirm('Bu baglantiyi silmek istediginizden emin misiniz? ' . $link->url)) {
$link->delete();
$this->info("Baglanti silindi.");
}

return 0;
}
}
Running the Command

First, find out the ID of the record you want to delete with link:list, then run the delete command. For example, let's delete the record with ID 2:


docker-compose exec app php artisan link:delete 2

This command asks for confirmation to delete the connection with ID number 2.


Frequently Asked Questions (FAQ)

  1. Why are artisan scripts preferred over web form?

Artisan commands require direct access to the server. This provides an additional layer of security for sensitive tasks such as database management. It is also a very fast and practical method for scheduled tasks (Cron Job) or prototyping.

  1. How to define command arguments (örnek: &#123;link_id&#125;) and its options?

Arguments define mandatory parameters as &#123;isim&#125;. Options define optional parameters such as {--isim} or {--isim=varsayilan}. Arguments depend on the order and options depend on the key-value pair.

  1. What is the Eloquent Model and why is it used?

Eloquent is Laravel's ORM (Object-Relational Mapper) tool. Maps database tables to classes (Model). So instead of writing SQL queries, you interact with the database with more readable and secure PHP codes like Link::find(1 or $link->save().

  1. What do return 0 and return 1 mean?

These values ​​report the exit code to the operating system where the command is run.

0 (Zero): It means the command completed successfully.

1 (One) or more: It means that the command ended with an error or abnormal condition. This is important in automation scenarios.


Result

By completing these steps, you have successfully set up database management via command line for your application. You can benefit from this powerful tool to speed up your application development processes. For more advanced tasks and automations, you can try it now on the GenixNode platform.