Reputation: 131
So, I have this code which is printing the various topics/threads started by the user.
It is looping over the Posts table that contains data related to posts.
In User column, it will display user_id
. But I want to access User table and display the user_name
column matching that user_id
. How to do this?
<table border="2">
<tr>
<th>Topic</th>
<th>User</th>
<th>Replies</th>
<th>Views</th>
<th>Last Update</th>
</tr>
@foreach($topics as $topic)
<tr>
<td><a href="topics/{{$topic->id}}">{{$topic->topic_title}}</a></td>
<td>{{$topic->id}}</td>
<td>0</td>
<td>0</td>
<td>{{$topic->updated_at}}</td>
</tr>
@endforeach
</table>
Controller's Code:
public function show($id)
{
$topics = Topic::where('board_id', $id)->get();
return view('boards.show')->with('topics', $topics);
}
Upvotes: 1
Views: 2328
Reputation: 887
You need to define relation in models first like this:
class User extends Model
{
public function post()
{
return $this->hasMany("App\Post");
}
}
class Post extends Model
{
public function user()
{
return $this->belongsTo("App\User");
}
}
then in the loop on the view side you can access user's data like this:
@foreach($topics as $topic)
<tr>
<td>{{$topic->user->name}}</td>
</tr>
@endforeach
You do not need to use "with" function in this case. you only need to fetch topics, pass them on to view, iterate through and you get the user's data
Upvotes: 0
Reputation: 891
In your Post model
public function user(){
$this->belongsTo(User::class);
}
In your blade {{$topic->user->name}}
<table border="2">
<tr>
<th>Topic</th>
<th>User</th>
<th>Replies</th>
<th>Views</th>
<th>Last Update</th>
</tr>
@foreach($topics as $topic)
<tr>
<td><a href="topics/{{$topic->id}}">{{$topic->topic_title}}</a></td>
<td>{{$topic->user->name}}</td>
<td>0</td>
<td>0</td>
<td>{{$topic->updated_at}}</td>
</tr>
@endforeach
Upvotes: 0
Reputation: 163978
In controller eager load user model:
$topics = Topic::where('board_id', $id)->with('user')->get();
In view:
<td>{{ $topic->user->user_name }}</td>
I assume you already have the user
relationship defined in Topic
model:
public function user()
{
return $this->belongsTo(User::class);
}
Upvotes: 2
Reputation: 5135
you can try something like this:
@foreach($topics as $topic)
@php $user = DB::table('User')->where('id', $topic->id)->first(); @endphp;
<tr>
<td><a href="topics/{{$topic->id}}">{{$topic->topic_title}}</a></td>
<td>{{ $user }}</td>
<td>0</td>
<td>0</td>
<td>{{$topic->updated_at}}</td>
</tr>
@endforeach
Upvotes: 0