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 ?

2 answers

  • answered 2022-05-06 01:20 Moustafa Mahmoud

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

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

    So by this way you could access it And i have a small advice for you change the name of your pivot table to user_event to be more clear

  • answered 2022-05-06 02:38 Kareem Salem

    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!

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum