How to Add New Records to Database with Laravel Eloquent?
Laravel Eloquent is a powerful tool that simplifies relational database operations. In this guide, you'll learn how to add new database records and manage relational data with Eloquent.
What Will You Learn in This Guide?
You will learn how to add a new record to the database using Laravel Eloquent ORM. You'll also discover how to create an Artisan command that allows new records to be saved along with their associated data, and how to update existing commands.
1. Updating Link Add Command (LinkNew)
Since the new links must be linked to a list, we need to update the existing LinkNew Artisan command.
Opening the Script:
docker-compose exec app nano app/Console/Commands/LinkNew.php
This command will open the file containing the link adding logic for editing.
Changing the handle() Method: After the link URL and description, the user should be asked for a list name and the list with this name should be found or created.
<?php
namespace App\Console\Commands;
use App\Models\Link;
use App\Models\LinkList; // 🔑 Yeni: LinkList modelini dahil eder
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class LinkNew extends Command
{
// ... (diger kisimlar)
public function handle()
{
$url = $this->ask('Link URL');
if (!filter_var($url, FILTER_VALIDATE_URL)) {
$this->error("Geçersiz URL. Çıkılıyor...");
return 1;
}
$description = $this->ask('Link Açıklaması');
// 🔑 Kullanıcıdan liste adı ister, boş bırakılırsa 'default' kullanılır
$list_name = $this->ask('Link Listesi (Varsayılan için boş bırakın)') ?? "default";
$this->info("Yeni Link Özeti:");
$this->info($url . ' - ' . $description);
$this->info("Listeleneceği yer: " . $list_name);
if ($this->confirm('Bu bilgiler doğru mu?')) {
// 🔑 LinkList modelini kullanarak liste kaydını bulur veya oluşturur
$list = LinkList::firstWhere('slug', $list_name);
if (!$list) {
$list = new LinkList();
$list->title = $list_name;
$list->slug = $list_name;
$list->save();
}
$link = new Link();
$link->url = $url;
$link->description = $description;
// 🔑 Yeni linki, LinkList modelinin ilişki metodu üzerinden kaydeder
$list->links()->save($link);
$this->info("Kaydedildi.");
}
return 0;
}
}
This code first finds/creates the new list, then saves the link by connecting it to the list with the relational links()->save() method.
2. Updating the Link Show Command (LinkShow)
While listing the links, let's update the LinkShow command to see which list they belong to.
Opening the Script:
docker-compose exec app nano app/Console/Commands/LinkShow.php
Opens the file that displays the links in a tabular form.
Changing the handle() Method:
Instead of just pulling the column names in the query, we should get the entire Eloquent collection. So we can access the relational data ($link->link_list->slug).
public function handle()
{
// 🔑 Yeni 'list' sütun başlığını ekler
$headers = [ 'id', 'url', 'list', 'description' ];
// 🔑 Tüm link kayıtlarını Eloquent koleksiyonu olarak çeker
$links = Link::all();
$table_rows = [];
foreach ($links as $link) {
// 🔑 Link koleksiyonunu döngü ile çevirir
$table_rows[] = [
$link->id,
$link->url,
// 🔑 İlişkisel modele (LinkList) slug alanı üzerinden erişir
$link->link_list->slug,
$link->description
];
}
$this->table($headers, $table_rows);
return 0;
}
This code enriches the output by taking the slug value of the list to which the link belongs and adding it to the table.
3. Testing the Adding New Record Process
Let's add a new record to the database using the updated link: new command.
Adding Link:
docker-compose exec app php artisan link:new
Run the command and answer the questions: URL, description, and list name (for example: genixnode_info).
Checking Records:
Verify that the record you added is listed with the list information it belongs to.
docker-compose exec app php artisan link:show
It checks that the newly added link appears in the table with the list name you entered.
Frequently Asked Questions (FAQ)
- What is the Difference Between
save()and Relationalsave()Methods?
The basic $model->save() method writes the current model record directly to the database. As for the relational save() ($parent->children()->save($child)), it automatically sets the key of the associated model (foreign key) and performs the registration.
- What does
firstWhere('slug', $list_name)do?
This method finds the first record in the LinkList model whose slug column is equal to the given $list_name. This is a short and readable way to write a conditional query.
- Why did we avoid using
Link::all()->toArray()?
When the toArray() method is used, Eloquent's associative links ($link->link_list) are lost. To access related data, it is necessary to pull all Eloquent objects and access the relationships within the (Link::all()) loop.
- What does return 1 in method
handle()mean?
In Artisan commands, 0 indicates successful exit, while 1 (or any non-zero value) indicates exit with an error. This is a standard convention for applications running in a scripting language.
Result
You can now safely enter data in one-to-many relationships with Laravel Eloquent. Enriching your command line tools in this way speeds up your development process. You can start using these tools on GenixNode virtual server instances immediately.

