Laravel Eloquent ORM: Updating Relational Database Records
Steps Followed by the User:
- Creating a new Artisan command (LinkUpdate) with
php artisan make:command. - Adding a mandatory argument ({link_id}) to the command signature.
- In the
handle()method, finding the record with the incominglink_id(Link::find()). - Requesting new values from the user (with the
ask()method) and getting approval (confirm()). - Checking for the existence of the new list name or creating the new list if it does not exist.
- Updating the relationship (
$link->link_list()->associate($list)) and making the records persistent (save()). - Testing the new command (
link:update 1).
Brief Technical Summary: This guide shows you how to update existing database records (Link model) within an Artisan command using Laravel Eloquent. The goal is to implement the use of the associate() method and the save() method to update the records associated with the feature (link_list()).
💡 What You Will Learn in This Guide
In this guide, you will see the integration of Laravel Eloquent ORM with Artisan Commands. You will learn how to update an existing database record, specifically another record (list) to which it is related. We will walk you through step by step how to make the updates permanent using the associate() and save() methods with interactive data retrieval from the user (ask and confirm).
⚙️ Step 1: Preparing the New Artisan Command
Let's create a new Artisan command to edit the connections in the database.
Starting the Script: Create a new console command named LinkUpdate in the project root directory.
docker-compose exec app php artisan make:command LinkUpdate
This command creates the file
app/Console/Commands/LinkUpdate.php.
Making Model Classes Available: Add the required Model classes at the beginning of the created file.
// app/Console/Commands/LinkUpdate.php
<?php
namespace App\Console\Commands;
use App\Models\Link;
use App\Models\LinkList;
use Illuminate\Console\Command;
Adding Command Signature: Update the signature so that the command takes a mandatory argument.
protected $signature = 'link:update {link_id}'; // Güncellenecek bağlantının ID'sini zorunlu kılar
This definition requires the user to enter an ID such as
link:update 5when running the command.
🧩 Step 2: Finding Records and Updating Interactively
Finding and Checking the Record: Search the record in the database with the incoming ID. If not found, show an error message and exit.
$link_id = $this->argument('link_id');
$link = Link::find($link_id);
if ($link === null) {
$this->error("Geçersiz veya mevcut olmayan bağlantı ID'si.");
return 1;
}
The
Link::find($link_id)command searches for records by primary key.
Getting Interactive Information from the User: Ask the user for the new description and list name.
$link->description = $this->ask('Bağlantı Açıklaması (Mevcutu korumak için ENTER)') ?? $link->description;
$list_name = $this->ask('Bağlantı Listesi (Mevcutu korumak için ENTER)') ?? $link->link_list->title;
$this->info("Açıklama: $link->description");
$this->info("Listelenen: " . $list_name);
The
ask()method asks the user to enter data via the terminal.
🔄 Step 3: Update and Save Relationship
Approve Update: Get a final confirmation from the user.
if ($this->confirm('Bu bilgiler doğru mu?')) {
// Güncelleme kodu buraya gelecek
}
Manage List Association and Update Record: Find or create a record with the new list name.
if ($this->confirm('Bu bilgiler doğru mu?')) {
$list = LinkList::firstWhere('slug', $list_name);
if (!$list) {
$list = new LinkList();
$list->title = $list_name;
$list->slug = $list_name;
$list->save();
}
$link->link_list()->associate($list)->save();
$this->info("Başarıyla Güncellendi.");
}
The
associate()method updates the foreign key of the model.save()reflects the changes to the database.
🧰 Step 4: Testing the Command
Viewing Existing Records:
docker-compose exec app php artisan link:show
Update Link:
docker-compose exec app php artisan link:update 1
Sample Terminal Output:
Link Description (Mevcutu korumak için ENTER):
> GenixNode Topluluk Sayfası
Link List (Mevcutu korumak için ENTER):
> genixnode-projeleri
Açıklama: GenixNode Topluluk Sayfası
Listelenen: genixnode-projeleri
Bu bilgiler doğru mu? (yes/no) [no]:
> y
Başarıyla Güncellendi.
You can see with
link:showthat the updated record is now assigned to the new list.
❓ Frequently Asked Questions (FAQ)
1. What exactly does the associate() method do?
Updates the belongsTo relationship of a model. For example, it matches the foreign key link_list_id in the Link model with the ID of the LinkList model you associate with.
2. What is the difference between save() and update()?
save() works with a single model instance. update() is for batch updating and does not trigger model events.
3. How do I make the user skip an argument?
You can make it optional by placing ? next to the argument name in the command signature.
4. How does $link->link_list->title work?
This works thanks to the Eloquent relationship. Laravel automatically resolves the link_list() relationship.
🏁 Result
With these steps, you have learned how to safely update database records and relationships in Laravel Eloquent. Now you can easily manage your data by using associate(), save() and confirm() methods on related data.
💡 Empower your projects with these advanced Eloquent methods on GenixNode virtual servers now! ☁️

