Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

zach1's avatar

question to relationships and views

Hi everybody

I’m a beginner and have one question to Eloquent. I have created three tables:

User (with attributes)

  • id
  • name

Event Table

  • id
  • name
  • date
  • active

Registration

  • id
  • user_id
  • event_id
  • registrationdate

If have setup a relationship between table event and registration. On the view I would like to show all active events available in table events and the information for the events the user already registered (table registration).

The authorization function of laravel is already working.

Do you know where I can get a example for the required code (query code and view)

Thanks Mario

0 likes
1 reply
tykus's avatar

You are almost there:

// User.php
public function events()
{
    return $this->belongsToMany('App\Event', 'registrations')->withPivot('registrationdate');
}

// Event.php
public function users()  // you could make this more readable by naming it 'attendees'
{
    return $this->belongsToMany('App\User', 'registrations');
}

// In your controller:
$user = User::find($id); // or Auth::user() ???
// Since you only want the active events, we need to get constrain the relationship:
$events = $user->events->filter(function($event)
{
    return $event->active;
}
return view('name_of_view, compact('user', 'events'));

// In your view:
{!! $user->name !!}'s Events
@foreach($events as $event)
    {!! $event->name !!}
    {!! $event->registrationdate !!}
@endforeach     

Please or to participate in this conversation.