Reputation: 131
I have following tables:
in user_events I insert assigned users to events, the table structure is so:
Schema::create('user_events', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');
$table->integer('event_id')->unsigned();
$table->foreign('event_id')->references('id')->on('events')->onUpdate('cascade')->onDelete('cascade');
$table->timestamps();
});
I want to create a page for auth user with his events.
To get Id's I use following relation in Model User:
public function userEvents() {
return $this->hasMany('App\Models\UserEvent');
}
Trought controller I get a list of Event id's.
My previous sources are: Laravel relation between 3 models
Laravel 5 relation between 3 tables
Laravel Eloquent Relation between 3 table
My question is, what is here to do to get throught this event id's event names?
Upvotes: 1
Views: 467
Reputation: 17658
By looking at your schema the relation should be many-to-many
instead of one-to-many
.
So your relation in User
model looks as:
public function events()
{
return $this->belongsToMany('App\Models\Event');
}
Then in your controller, get all the events of authenticated user by:
$events = auth()->user()->events; // returns collection of Event model
Upvotes: 0
Reputation: 67505
You could pluck
the name
from collection returned by $user->userEvents
:
$user->userEvents->pluck('name');
Hope this helps.
Upvotes: 1