Can you dd() your index function and display over here because are you sure your getting a collection of datas.
Mar 22, 2019
4
Level 3
Getting Null in eloquent relation data after 3 records !
For some reason, I am getting null as eloquent relation data.
below is the code i have written.
public function index()
{
return response()->json(
[
'blogs' => Article::with(['author', 'moderator'])->paginate(10)
],
200
);
}
and my article model file is like this:
class Article extends Model
{
protected $guarded = [];
public function getTags()
{
return $this->hasMany(Tag::class);
}
public function getCategory()
{
return $this->hasOne(Category::class);
}
public function author()
{
return $this->hasOne(User::class, 'id');
}
public function moderator()
{
return $this->hasOne(User::class, 'id');
}
}
and output is like this:
blogs
current_page 1
data
0 {…}
1 {…}
2 {…}
3 {…}
4 {…}
5
id 6
title "Quasi sint dicta voluptatibus perspiciatis impedit. Eos quo aliquam impedit hic."
slug "Quasi-sint-dicta-voluptatibus-perspiciatis-impedit.-Eos-quo-aliquam-impedit-hic."
banner "public/uploads/ba/\62814d0ee1523633207700445c891356.jpg"
description "Aperiam eveniet nobis corrupti dignissimos fugiat consectetur."
category_id 95
body "Amet et beatae id omnis aut nulla qui praesentium. Quos autem est eos dolores quibusdam. Et rerum magnam doloribus non quibusdam omnis nulla."
views 1
status 1
author_id 1
moderator_id 3
created_at "2019-03-22 08:48:30"
updated_at "2019-03-22 08:48:30"
author null
moderator null
6 {…}
7 {…}
8 {…}
9 {…}
first_page_url "http://localhost:8000/blogs?page=1"
from 1
last_page 5
last_page_url "http://localhost:8000/blogs?page=5"
next_page_url "http://localhost:8000/blogs?page=2"
path "http://localhost:8000/blogs"
per_page 10
prev_page_url null
to 10
total
Level 3
i think the problem is that the relationship foreign keys are not set right. The second argument of hasOne() should be the explicit foreign key, which in this case is set as the id of the table Article, where it should be the moderator_id or the author_id. And if i understand correctly, the article belongs to a User that can be an Author or a Moderator. Try this and see if it works:
Article model:
public function author()
{
return $this->belongsTo(User::class, 'author_id');
}
public function moderator()
{
return $this->belongsTo(User::class, 'moderator_id');
}
And in your User Model:
public function articleAsAuthor()
{
return $this->hasOne(Article::class, 'author_id');
}
public function articleAsModerator()
{
return $this->hasOne(Article::class, 'moderator_id');
}
1 like
Please or to participate in this conversation.