remove ->where('bookSlug', $this->book->bookSlug);?
public function chapter() {
return $this->hasOne(Chapters::class, 'chapterNumber', 'chapterId');
}
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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?
Please or to participate in this conversation.