The issue is that the user_id column is not being selected in the main query, so the related query is not able to find the user. To solve this, you can select the user_id column in the main query and then use the map method to filter the results to only include the desired columns. Here's an example:
public function index()
{
$threads = Thread::query()
->select('id', 'title', 'body', 'slug', 'user_id')
->with('user:id,username,email')
->latest()
->paginate(20);
$threads = $threads->map(function ($thread) {
return [
'id' => $thread->id,
'title' => $thread->title,
'body' => $thread->body,
'slug' => $thread->slug,
'user' => [
'username' => $thread->user->username,
'email' => $thread->user->email,
],
];
});
return Inertia::render('Discussion/Threads/Index', [
'threads' => $threads,
]);
}
In this example, we select the id, title, body, slug, and user_id columns in the main query. Then, in the with method, we select only the id, username, and email columns from the users table.
After fetching the results, we use the map method to filter the results to only include the desired columns. In this case, we include the id, title, body, and slug columns from the threads table, and the username and email columns from the users table.
Finally, we return the filtered results to the view.