Table of Contents
Inside this article we will see the concept i.e Eloquent one-to-many relationship in Laravel 10 Tutorial. Article contains the classified information i.e What is One to Many Relationship and How it works in laravel.
We will see the complete Idea of Best practices for using one-to-many relationships in Laravel 10.
In Laravel, 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).
For this tutorial we will consider a posts table and a comments table. This means a single post can have multiple comments.
Learn More –
- Laravel 10 One to One Eloquent Relationship Tutorial
- Laravel 10 FullCalendar Ajax CRUD Tutorial Example
- Laravel 10 How To Add Google reCaptcha v3 Validation
- How To Call MySQL Stored Procedure in Laravel 10 Tutorial
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
Create Migrations
We need to create two migration files.
- Migration file for Posts table
- Migration file for Comments table
Open project terminal and run these migrations command.
$ php artisan make:migration CreatePostsTable
$ php artisan make:migration CreateCommentsTable
It will create two files 2023_03_06_150722_create_posts_table.php & 2023_03_06_150840_create_comments_table.php inside /database/migrations folder.
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() { 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() { 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() { 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() { Schema::dropIfExists('comments'); } };
Run Migrations
Next, we need to migrate migrations.
$ php artisan migrate
This command will create tables inside database.
Create Model & Add Relationships
Next,
We need to create two models. 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 & 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; 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.
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; 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);
Controller Usage
Now, let’s test with a dummy application controller file.
Open any controller say DataController.php file from /app/Http/Controllers folder.
Here, we have created two methods in which we use 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); } }
Few details,
- 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
Open project to terminal and type the command to start development server
$ php artisan serve
URLs
Get Comments – http://127.0.0.1:8000/get-comments/1
Get Post detail– http://127.0.0.1:8000/get-post/1
We hope this article helped you to learn 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.