How to Create a One-to-Many Relationship with Laravel Eloquent?
In this guide, you will learn how to create a one-to-many relationship between a list and the links of this list in your database using Laravel Eloquent ORM. You will also discover how you can manage these relationships in the database and connect your links to lists.
What Will You Learn in This Guide?
You will learn how to establish a one-to-many relationship between a list (LinkList) and links (Link) in Laravel Eloquent ORM. You will follow the steps of managing relational data, creating new model and migration files, and working with Eloquent relationships.
1. Creating the LinkList Model and Editing the Command
We need to create a new Eloquent Model that represents the List structure in which we will group the links.
Starting New Model:
Create a new model in the project directory with the command:
docker-compose exec app php artisan make:model LinkList
This command will create the file app/Models/LinkList.php. Since the word List is reserved in PHP, the name LinkList is used.
Renaming Existing Command:
When you notice the app/Console/Commands/LinkList.php file in the project directory, this file contains CLI commands. This class is used to list links in the database.
To change the name of the command, run this command:
mv app/Console/Commands/LinkList.php app/Console/Commands/LinkShow.php
Afterwards, open the file and change the class name from LinkList to LinkShow. Define the new command as follows, also updating the command signature:
<?php
namespace App\Console\Commands;
use App\Models\Link;
use Illuminate\Console\Command;
class LinkShow extends Command
{
protected $signature = 'link:show';
protected $description = 'Veritabanındaki linkleri listele';
public function __construct()
{
parent::__construct();
}
public function handle()
{
$headers = ['id', 'url', 'description'];
$links = Link::all(['id', 'url', 'description'])->toArray();
$this->table($headers, $links);
return 0;
}
}
With this change, you will now be able to see the list of links by running the link:show command.
2. Preparing Database Migrations
To establish the relationship, we must make the necessary structural changes in both tables.
Creating the LinkList Table Migration:
Create a migration file for the new LinkList model:
docker-compose exec app php artisan make:migration create_link_lists_table
Editing the LinkList Migration File:
Open the newly created migration file and define the columns of the list table:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateLinkListsTable extends Migration
{
public function up()
{
Schema::create('link_lists', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->string('title', 60);
$table->string('slug', 60)->unique();
$table->text('description')->nullable();
});
}
public function down()
{
Schema::dropIfExists('link_lists');
}
}
Update Existing Links Migration:
Add the foreign key of the One-to-Many relationship by opening the existing migration file create_links_table.php. The "many" side (Links) holds the key.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use App\Models\LinkList;
class CreateLinksTable extends Migration
{
public function up()
{
Schema::create('links', function (Blueprint $table) {
$table->id();
$table->string('url', 200);
$table->text('description');
$table->foreignIdFor(LinkList::class); // 🔑 İlişkili listeyi ekler
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('links');
}
}
Updating the Database:
Clean up the database and run the migrations again:
docker-compose exec app php artisan db:wipe
docker-compose exec app php artisan migrate
3. Defining Eloquent Model Relationships
Once the tables are prepared, let's use the power of Eloquent by defining the relationship between models.
LinkList Model (One-to-One) Relationship:
Open app/Models/LinkList.php and add a method that returns multiple records of the Link model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class LinkList extends Model
{
use HasFactory;
public function links()
{
// 🔑 Bir listenin birden çok linki olabilir
return $this->hasMany(Link::class);
}
}
Link Model (Multi-Party) Relationship:
Open app/Models/Link.php and add a method that returns a single list to which the link belongs:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Link extends Model
{
public function link_list()
{
// 🔑 Bir link yalnızca tek bir listeye ait olabilir
return $this->belongsTo(LinkList::class);
}
}
4. Testing the Adding New Record Process
Let's test the process of adding a new link.
Adding Link:
docker-compose exec app php artisan link:new
Enter information such as URL, description, and list name on the command line.
Checking Records:
Also view the list that the record you added is associated with:
docker-compose exec app php artisan link:show
Frequently Asked Questions (FAQ)
- What is the difference between
save()andlinks()->save()?
save() saves the current model directly to the database. links()->save() connects and saves the associated data (i.e. link) to another model.
- What does
foreignIdFor(LinkList::class)do?
This method creates a foreign key column that holds the reference to the LinkList model.
- How does
firstWhere('slug', $list_name)work?
This method finds the first record in the LinkList model whose slug column matches the given $list_name. This provides quick access to relational data.
- How do relationships with Eloquent work?
The hasMany method allows a model to have more than one relationship, while the belongsTo method ensures that a model belongs to another model.
- What does the
db:wipecommand do? Is it risky?
db:wipe completely deletes all tables and data in the database. Useful for resetting tables in the development environment. It is definitely not recommended to use it in live systems as it will cause data loss.
Result
You can now securely manage one-to-many relationships with Laravel Eloquent and save relational data when adding data to your database. You can speed up your development processes by using these tools. You can start immediately for similar infrastructures on the GenixNode platform.

