Get name from second table (belongsTo relationShip)

Posted 8 months ago by Stank0V01

Hello guys, i have problem with displaying data from second table! So here is my db structure first:

category:
\id
\name
\parent_id
\vissible

notifications:
\id
\title
\content

category_notification:
\category_id
\notification_id

Model examples

Notification model:

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function categories() {
        return $this->belongsToMany(Category::class,'category_notification');
    }


Category model:

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function notifications() {
        return $this->belongsToMany(Notification::class);
    }

My code:

$notifications = Notification::with('categories')->get();

foreach($notifications as $nft) {

 echo $nft->name.'<br>'.$nft->categories->name

}

What im doing wrong?

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.