Search code examples
phpmysqllaravelormlaravel-9

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

  • 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!