Laravel One To Many Relationship Example Tutorial

Laravel One To Many Relationship, laravel many to many relationship, laravel hasmanythrough, laravel one to many polymorphic, laravel one to one polymorphic, Laravel Many To Many Polymorphic Tutorial Example, laravel hasonethrough, Laravel PDF Generator

I will talk about Laravel One To Many Relationship Example Tutorial in this post.

Laravel has ORM model with eloquent concept which allows us to handle one to many relationship seamlessly.

Several types of relations are one to one, one to many, many to many, polymorphic etc.

I will show you a practical example how one to many relation in database works in laravel project.

One To Many Relationship

As the name suggests, one to many means a single row from the first table has relationship with one or more than one rows of the second table.

Best example to understand this concept is of relationship between a blog post and it’s comments.

Let us assume that first table is posts and it contains id and post_name columns.

Second table is comments and it has id, post_id and comment three columns.

Now post have id and it’s name. One post can have one or more comments. Comments are in second table. So, id is the unique for comments table, but value of post_id will be same for comments on single post.

To understand this scenario easily, see the below image.

laravel one to many relationship

So in the image, two tables are there : posts and comments

Two posts are there : laravel and android

Four comments are there : two for laravel and two for android

Thus, one row of post is associated with one or more rows of comments tables. This is called laravel one to many relationship.

Now let us put this heavy theory into reality but first, see the final result of this example in below video.

Step 1. New project and Database

As always, fire up the project creation command.

laravel new laraonetomany

Now you have a fresh new laravel project called “laraonetomany

Time to create new database. For this, you need to go to your database management tool.

For mac book, I am using sequel pro, most of developers use phpMyAdmin and if you are using phpMyAdmin or any other then it is ok, process for all tools are same.

Just make a new database and give it a name like “laraonetomany

Now come to your favorite code editor, mine is visual studio code. Open your laravel project and change the below lines from .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laraonetomany
DB_USERNAME=root
DB_PASSWORD=

You need to update all the above fields as per your machine configurations.

Once you modify these fields, your database and laravel project should have connected with each other.

Step 2. Creating Post and Comment Tables

Now let us create two tables : posts and comments

Run the following command first,

php artisan make:migration create_posts_table

This command should have created a new migration file but we will see it later.

Again go to terminal and run the following

php artisan make:migration create_comments_table

After this go to database->migrations directory.  You will find two migrations files here : one is timestamp_create_posts_table.php and another is timestamp_create_comments_table.php

First of all, open timestamp_create_posts_table.php file and add the below code

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string("post_name");
            $table->timestamps();
            
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

Look at the up() method. It contains three lines which tells us that posts table will have columns like id, post_name and timestamp.

Now open up timestamp_create_comments_table.php file and write down the following source lines in it

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCommentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('post_id')->unsigned();
            $table->string("comment");
            $table->timestamps();
            $table->foreign('post_id')->references('id')->on('posts')
                   ->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('comments');
    }
}

Again look at the up() functions. It has the names of the comments table columns like id, post_id, comment, timestamps.

Now consider the following lines

$table->foreign('post_id')->references('id')->on('posts')
                   ->onDelete('cascade');

Above line tells compiler that post_id from comments table is referencing the id column from posts table.

After this much coding, trigger the below command

php artisan migrate

This will create the tables posts and comments in our “laraonetomany” database.

Step 3. Making Required Model Files

Run the following command

php artisan make:model Post

Then run the below command

php artisan make:model Comment

First command will make a model Post.php and second will create Comment.php file.

Now navigate to app->Post.php file and write down the below snippet

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
     /**
     * Get the comments for the blog post.
     */
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}

Look at the comments() function. It includes the usage of hasMany() method.

hasMany() method tells compiler that any row from posts table have relationship with many rows of comments table.

So this is the core concept of one to many relationship. This hasMany() method will allow us to fetch many records from comments table.

Inverse of One to Many Relationship

There is one method called “belongsTo()” , which allows us to perform reverse operation of one to many relationship.

Now go to app->Comment.php file and write down the following code snippet

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    /**
     * Get the post that owns the comment.
     */
    public function post()
    {
        return $this->belongsTo(Post::class);
    }
}

Here, we have used belongsTo()” method. It simply says that rows from comments have one to many relation with single row of posts table.

Step 4. Manually adding records in database

Now we need to add some records in database manually.

I suggest you to add two rows in the posts table and four rows in the comments table.

Two comments should be for both post records.

In short, you need to add rows in both tables as per the below image.

laravel one to many relationship

Step 5. Route and Controller Works

Let us define one route to open view page. Go to routes->web.php file.

Add the below line of code in this route file.

Route::get('comments','CommentsController@commentPost');

This line is telling compiler to execute commentPost() function from CommentsController file when user runs http://127.0.0.1:8000/comments in the web browser.

Whole source code for web.php file is as the below

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});
Route::get('comments','CommentsController@commentPost');

Now let us create a controller file.

Run the following command in terminal

php artisan make:controller CommentsController

After this, you will find a CommentsController.php file inside app->Http->Controllers directory.

Write the following source lines in this file.

<?php

namespace App\Http\Controllers;

use App\Post;
use App\Comment;
use Illuminate\Http\Request;

class CommentsController extends Controller
{
    //
    public function commentPost()
    {
 
        $postFirst = Post::find(1);
        $commentsFirst = $postFirst->comments;
      
        $postSecond = Post::find(2);
        $commentsSecond = $postSecond->comments;

        $allposts = Post::all();
        $allcomments = Comment::all();
     
        return view('index',compact('commentsFirst','commentsSecond','allposts','allcomments'));
       
    }
}

Look at the first line of commentPost() function. It will find all the comments for first post (post which have 1 id in posts table and post_id is also 1 in comments table).

$postFirst will get the array from comments table (it includes all the fields from table like id, post_id, comments ,timestamp etc.). Second line will help us to sort out comments from that array.

Third line fetch all the rows from comments table where post_id is 2 which means that id is 2 in posts table.

Fourth line will again sort out the comment field from $postSecond

Fifth line will fetch all the records from posts table and last one will get the every records from comments table.

Finally, return statement will open the index.blade.php file. It will also send some variables as a parameter to view file.

Step 6. Last View Index File

This is our last step of this tutorial.

Under resources->views directory, make a new file and give it a name like index.blade.php

Add the following source lines in this file.

<html>
<head>
   
</head>
<style>
 
 
</style>

<h1> Laravel One to Many Example </h1>

<h3> All Posts </h3>

@foreach ($allposts as $post)
<li> 
 
    {{ $post->post_name}}  
 
    </a>
 
</li>
@endforeach

<h3> All Comments </h3>

@foreach ($allcomments as $comment)
<li> 
 
    {{ $comment->comment}}  
 
    </a>
 
</li>
@endforeach

<h3> Below are comments from Laravel Post whose id is 1 </h3>
@foreach ($commentsFirst as $comment)
<li> 
 
    {{ $comment->comment}}  
 
    </a>
 
</li>
@endforeach


<h3> Below are comments from Android Post whose id is 2 </h3>


@foreach ($commentsSecond as $comment)
<li> 
 
    {{ $comment->comment}}  
 
    </a>
 
</li>
@endforeach

</body>
</html>

This file will generate the final look and feel that you have already shown in the output video.

We will get all the variables that we have passed in the return statement of the controller file.

Using these variable, we will print appropriate values.

Download Code For laravel one to many relationship

https://github.com/demonuts/Laravel-One-to-many-relationship-example