Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

zainshabir00's avatar

Laravel with query relationship not working in JSON response API

I have 3 tables named books, chapters & hadiths. These tables are connected. When i try to directly access chapter relationship in my view balde file $hadiths foreach loop like this $hadith->chapter, it gives me right data of chapter which belongs to hadith. But when i try to get relation in my Hadith query using with relation to get hadith's chapter in JSON response, then it's giving me ErrorException: Trying to get property 'bookSlug' of non-object. My relationships:

class Hadith extends Model {
    // Get the book that owns the hadith.
    public function book() {
        return $this->belongsTo(Books::class, 'bookSlug', 'bookSlug');
    }

    // Get the chapter that owns the hadith.
    public function chapter() {
        return $this->belongsTo(Chapters::class, 'chapterNumber', 'chapterId')->where('bookSlug', $this->book->bookSlug);
    }
}

`Controller`
$hadiths = Hadith::with('chapter')->orderBy('hadithNumber', 'ASC')->get();

The error: Trying to get property 'bookSlug' of non-object.

Why it's working if i directly access relationship in foreach loop and not working using with relation to get chapter in JSON response? Any help? I am stuck?

0 likes
7 replies
frankielee's avatar

remove ->where('bookSlug', $this->book->bookSlug);?

  public function chapter() {
        return $this->hasOne(Chapters::class, 'chapterNumber', 'chapterId');
    }

zainshabir00's avatar

Removing where clause will give me multiple chapters.

frankielee's avatar

What is the difference between these bookSlug?

1st: return $this->belongsTo(Books::class, 'bookSlug', 'bookSlug');

2nd: where('bookSlug', $this->book->bookSlug)

Maybe you can try to define a new relationship

public function filterChapter(){
	   return $this->belongsTo(Chapters::class, 'chapterNumber', 'chapterId')
					->join('books','chapters.bookSlug','books.bookSlug');
}
zainshabir00's avatar

My tables books, chapters & hadiths are connected with bookSlug column, it means my those 3 tables have bookSlug column. And my hadiths & chapters are connected with column chapterId & chapterNumber.

zainshabir00's avatar

filterChapter working same as chapter was working (i mean wrong)

SilenceBringer's avatar

@zainshabir00 inside relationship declaration you can't use any model attributes for query, because they returns null (your $this->book in chapter declaration returns null)

zainshabir00's avatar

So, how can I achieve this? I want the chapter relation in my JSON response.

Please or to participate in this conversation.