You should show the relationship code too
But something looks strange (probably cause here is 05.30 😂)
In tinker you search for the user with id 1 and you get the user with ID 4.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Learning how to retrieve data from db tables has been the biggest challenge for me. I'm not referring the simple default way.
Here I have a table of events, and I have no problem displaying everything in the table, but I want to also display the user who is associated with that event, but I'm thrown off by the id. I can get all the users, but not the user associated with the event with the id of 1. Also I can't use a foreach to loop over the data as we did in my previous question because this isn't an array.
So here's my index method. This is easy. I understand every bit of this code.
public function index()
{
$users = User::with('events')->get();
return view('pages.events.index', compact( 'users'));
}
But my head explodes when I get to the show method where I am trying to display the user associated with the event..
I have tried a several different ways that don't work. I'll copy my show method of each attempt individually below. but first I want to post output of tinker to show that the relationship is there, I just don't know how to write it.
>>> $user = User::find(1);
=> App\User {#4139
id: 1,
name: "David McGlone",
email: "[email protected]",
: null,
img: null,
created_at: "2020-09-04 17:50:47",
updated_at: "2020-09-04 17:50:47",
}
>>> $user->events
=> Illuminate\Database\Eloquent\Collection {#4137
all: [
App\Event {#4138
id: 1,
user_id: null,
title: "First Event",
date: "2008-11-01 00:00:00",
description: "Organized by david User id - 1",
location: "Home",
remember_token: null,
created_at: "2020-09-04 17:50:47",
updated_at: "2020-09-04 17:50:47",
pivot: Illuminate\Database\Eloquent\Relations\Pivot {#4135
user_id: 1,
event_id: 1,
},
},
],
}
>>>
Event.php
public function events{
$this->hasMany('App\Event')
}
I found that this grabs the user, BUT it's grabbing the user with the same id as the event.
public function show($id)
{
$events = Event::with('users')->findOrFail($id);
var_dump($events);
}
Same as above.
public function show($id)
{
$events = Event::with('users')->findOrFail($id)->get();
var_dump($events);
}
I can't remember what this did, but i'm sure the experiences ones can see it was wrong.
public function show($id)
{
$events = Event::findOrFail($id);
$users = User::with('events')->get($id);
return view('pages.events.show', compact( 'events', 'users'));
}
Please or to participate in this conversation.