Fetch data with model relationship in laravel 7

Hello World, Welcome to projectsplaza.com. Today we will discuss how we can fetch data with the model relationship in laravel 7. In this tutorial, we will create an example of hasMany and belongsTo model relationship.

hasMany Relationship

Suppose you have a blog website and you want to fetch comments of a specific post on the post detail page. In this scenario, you should have two models, Post and Comment respectively. We know that a single post has many comments so we will define the hasMany relationship in the post model.

// Define relation -  Post Model
public function comments(){
    return $this->hasMany(App\Comment);

In post detail page, You will have post detail instance, say $post. We will user $post to fetch comments with the help of model relationship.

//  Fetch Comments  -  Post Detail Page
@foreach($post->comments as $comment)


Now we want to show the email of comment sender. In this case, we will use a belongsTo relationship. We know that every comment belongs to the user. So we will define the belongsTo relationship in the Comment model.

//  Define relation -  Comment Model
public function user(){
    return $this->belongsTo(App\User);

In the post detail page, You will have a post detail instance, say $post. We will user $post to fetch comments with the help of the model relationship.

//  Fetch User email  -  Post Detail Page
@foreach($post->comments as $comment)
    {{$comment->comment_text}} // Show Comment
    {{$comment->user->email}}   // Show user email

I hope you enjoyed this tutorial. Please add your feedback in the comment section. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *