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 ?
CodePudding user response:
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
CodePudding user response:
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!