Database relationships are an essential component of web application development, allowing you to efficiently model complicated data structures. The one-to-many relationship, in which one entry in one table is related with several records in another table, is one of the most common.
One-to-Many Eloquent Relationship is a type of database relationship in which one model is associated with multiple instances of another model. In this type of relationship, a single record from one table (parent model) has many related records in another table (child model).
Laravel, a powerful PHP framework, makes it easier to construct such associations with its Eloquent ORM. In this tutorial, we will walk you through the process of constructing a one-to-many Eloquent connection in Laravel 10, allowing you to manage and retrieve related data from your database more quickly.
Read More: Laravel 10 One to One Eloquent Relationship Tutorial
For this tutorial we will consider a posts table and a comments table. This means a single post can have multiple comments.
Let’s get started.
Laravel Installation
Open terminal and run this command to create a laravel project.
composer create-project laravel/laravel myblog
It will create a project folder with name myblog inside your local system.
To start the development server of laravel –
php artisan serve
URL: http://127.0.0.1:8000
Assuming laravel already installed inside your system.
Create Database & Connect
To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.
CREATE DATABASE laravel_app;
To connect database with application, Open .env file from application root. Search for DB_ and update your details.
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=laravel_app DB_USERNAME=root DB_PASSWORD=root
Setup Migrations for One-to-Many Relationship
You need to create two migration files,
- Migration file for Posts table
- Migration file for Comments table
Open project terminal and run these migration commands,
php artisan make:migration CreatePostsTable
php artisan make:migration CreateCommentsTable
It will create two files xxx_create_posts_table.php & xxx_create_comments_table.php inside /database/migrations folder.
Read More: Laravel 10 Call MySQL Stored Procedure Example Tutorial
Open xxx_create_posts_table.php and write this complete code into it,
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up(): void { Schema::create('posts', function (Blueprint $table) { $table->id(); $table->string("title"); $table->text("description")->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down(): void { Schema::dropIfExists('posts'); } };
Next,
Open xxx_create_comments_table.php and write this code into it,
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up(): void { Schema::create('comments', function (Blueprint $table) { $table->id(); $table->foreignId('post_id')->constrained('posts'); $table->string("comment"); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down(): void { Schema::dropIfExists('comments'); } };
Run Migrations
Next, need to migrate migrations.
php artisan migrate
This command will create tables inside database.
Next,
Create Model & Add One-to-Many Relationship with Inverse
Back to project terminal and run these artisan commands,
php artisan make:model Post
php artisan make:model Comment
This command will create two files Post.php and Comment.php inside /app/Models folder.
Open Post.php and write this complete code into it.
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasMany; use App\Models\Comment; class Post extends Model { use HasFactory; /** * The attributes that are mass assignable. * * @var array<int, string> */ protected $fillable = [ "title", "description" ]; /** * Get the comments for the blog post. */ public function comments(): HasMany { return $this->hasMany(Comment::class); } }
$this->hasMany(Comment::class); This means that one Post can have many comments. This is establishing One-To-Many Relationship.
Read More: Laravel 10 FullCalendar Ajax CRUD Tutorial Example
Usage
$comments = Post::find(1)->comments;
Inverse Relationship One-To-Many
Open Comment.php model file and write this complete code into it,
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use App\Models\Post; class Comment extends Model { use HasFactory; /** * The attributes that are mass assignable. * * @var array<int, string> */ protected $fillable = [ "post_id", "comment" ]; /** * Get the post that owns the comment. */ public function post(): BelongsTo { return $this->belongsTo(Post::class); } }
$this->belongsTo(Post::class); This means a comment has a associated post with it. This is establishing Inverse of One-To-Many Relationship.
Usage
$comment = Comment::find(1);
How To Use Relations in Laravel Controller?
Open any controller say DataController.php file from /app/Http/Controllers folder.
Here, you can see two methods in which we used model methods as a property.
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Post; use App\Models\Comment; class DataController extends Controller { public function getComments($post_id) { // Passing post id into find() return Post::find($post_id)->comments; } public function getPost($comment_id) { // Passing comment id into find() return Comment::find($comment_id); } }
Explanation,
- Post::find($post_id)->comments; It will find comments detail values by post id. One to Many
- Comment::find($comment_id)->post; It will find post detail by comment id. Inverse of One to Many / Belongs To
Add Routes
Open web.php from /routes folder and add these routes into it,
//... use App\Http\Controllers\DataController; Route::get('get-comments/{id}', [DataController::class, 'getComments']); Route::get('get-post/{id}', [DataController::class, 'getPost']); //...
Application Testing
Run this command into project terminal to start development server,
php artisan serve
Test URLs
Get Comments – http://127.0.0.1:8000/get-comments/1
Get Post detail – http://127.0.0.1:8000/get-post/1
That’s it.
We hope this article helped you to learn about Laravel 10 One to Many Eloquent Relationship Tutorial in a very detailed way.
Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.
If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.