How to get Child Table Data in Laravel by Relationship Tutorial

In this tutorial we will discuss, how to get child table data in laravel using relationship.

Laravel get child table data using relationship

We use various type of relationships for getting child table data in laravel here discuss two main relationship one-to-one(hasOne) and one-to-many(hasMany).

hasOne() relationship use for getting only one relation data from child table and hasMany() relationship use for getting all related relation data see in example.

Tables

  videos: id, title, description
  comments: id, video_id, content

Video Model

In our Video model we have two relationship for getting comments data first is comment which get only first match comment data and second is comments which get all comments with related model

<?php

namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class Video extends Model {
    
    public function comment() {
        return $this->hasOne(Comment::class);
    }

    public function comments() {
        return $this->hasMany(Comment::class);
    }
}

Comment Model

<?php

namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class Comment extends Model {
    
}

Video Controller

Now we get videos and child table(comments) data in video controller

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Video;

class VideoController extends Controller{
  public function index(){
    $videos = Video::with('comment', 'comments')->get();
    dd($videos);
  }
}

You read this tutorial on advanced web tuts provided by anmol sharma.

php laravel developer anmol sharma

Anmol Sharma

I am a software engineer and have experience in web development technologies like php, Laravel, Codeigniter, javascript, jquery, bootstrap and I like to share my deep knowledge by these blogs.

Random tutorial links