Search code examples
laravellaravel-8laravel-7

laravel how to show one to many data in view (fetch ) in view


hello I'm trying to fetch one to many data in view like post with this feast comment shooed be show in view

iam able to get value in array now i what to show in view

my array controller

public function data($id)
{
     
 $post= User::with(['Comments'=>function($query){ 
    $query->first(); 
}])->find($id);

 dd($post->toArray());

}

array data

array:53 [▼
  "id" => 39
  "name" => "KUMAR"
  "post" => "hello word "
  "created_at" => "2022-02-11T02:38:51.000000Z"
  "updated_at" => "2022-02-11T10:05:26.000000Z"
  "comments" => array:1 [▼
    0 => array:13 [▼
      "id" => 6
      "user_id" => "39"
      "comment" => "good post"
      "created_at" => "2022-02-11T15:13:51.000000Z"
      "updated_at" => "2022-02-11T15:13:51.000000Z"
    ]
  ]
]

my view Controller

public function data($id)
{
     
 $post= User::with(['Comments'=>function($query){ 
    $query->first(); 
}])->find($id);

 return view('user.post',compact('post'));

}


Solution

  • So your User model already has this comments relationship

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

    You can add this firstComment relatioship

        public function firstComment()
        {
            return $this->hasOne(Comment::class)->oldest(); // or ->latest()
        }
    

    Then fetch your User this way

    $post = User::with(['firstComment'])->find($id);
    
    dump($post);
    dd($post->firstComment);