'How To Access A Column In M-M Relationship Table In Laravel

I made a many-to-many relationship in laravel, where users can make announcements on an event.

The problem is that I want to retrieve the announcement message from the database using the relationship.

Here is my code:

Database Migration:

   Schema::create('announcements', function (Blueprint $table) {
        $table->id();
        $table->text("message");
        $table->foreignId('user_id')->constrained()->cascadeOnDelete()->cascadeOnUpdate();
        $table->foreignId('event_id')->constrained()->cascadeOnDelete()->cascadeOnUpdate();
        $table->timestamps();
    });

Event Model:

public function announcements() {
    return $this->belongsToMany(User::class, 'announcements');
}

User Model:

public function announcements() {
    return $this->belongsToMany(Event::class, 'announcements');
}

Events Controller:

 public function getEventAnnouncements($id) {
    $event = Event::find($id);


    $ann = [];
    $event->announcements->each(function ($a) use ($ann) {
        // echo $a;
        // $ann += $a->message;
    });

    return $ann;
}

What Should I Write In The Controller To Get The Content Of messages Column ?



Solution 1:[1]

I Found The Solution!

First I was supposed to add a pivot in the Models

Event Model:

public function announcements() {
   return $this->belongsToMany(User::class, 'announcements')->withPivot('message');
}

User Model:

public function announcements() {
    return $this->belongsToMany(Event::class, 'announcements')->withPivot('message');
}

And Finally Loop Through The Results To Get Messages.

EventsController:

    $ann = [];
    foreach ($event->announcements as $a) {
        $ann[] = [
            "name" => $a->name,
            "announcement" => $a->pivot->message,
            "created_at" => $a->pivot->created_at,
        ];
    }

It Worked Fine!

Solution 2:[2]

You could access the message attribute by using the pivot keyword.

$event->announcements->pivot->message;

So by this way, you can access it. And I have a small piece of advice for you change the name of your pivot table to user_event to be clear

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kareem Salem
Solution 2 Karl Hill