Home Laravel relation between 3 tables?
Reply: 2

Laravel relation between 3 tables?

nowilius Published in 2016-12-10 11:48:49Z

I have following tables:

  1. users (classic laravel table)
  2. events
  3. user_events

in user_events I insert assigned users to events, the table structure is so:

Schema::create('user_events', function (Blueprint $table) {

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?

Amit Gupta
Amit Gupta Reply to 2016-12-10 14:47:56Z

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
Zakaria Acharki
Zakaria Acharki Reply to 2016-12-10 11:52:29Z

You could pluck the name from collection returned by $user->userEvents :


Hope this helps.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.304599 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO