Support the ongoing development of Laravel.io →
posted 8 years ago
Eloquent

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) {
            $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 question is, what is here to do to get throught this event id's event names?

Thank you in advance.

Last updated 3 years ago.
0
Solution

erdely said:

I have following tables:

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

public function userEvents()
{
  return $this->hasMany('App\Models\UserEvent');
}

// user event model

public function user()
{
  return $this->belongsTo('App\Models\User');
}

public function event()
{
  return $this->belongsTo('App\Models\Event');
}

// example of resultset
$user_events = UserEvent:get();

foreach ($user_events as $user_event)
{
  echo $user_event->user->name;           // displays the user's name that is associated with user_event
  echo $user_event->event->name;         // displays the even'ts name that is associated with user_event
}

hope that helps

0

It works, many thanks :)

0

Sign in to participate in this thread!

Eventy

Your banner here too?

erdely erdely Joined 7 Nov 2016

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.