user10555285
user10555285

Reputation:

Trying to get username from User model using user_id Laravel

I'm getting an error undefined variable when I'm trying to get username ($user->name) from User model using id which is foreign key ($feedback->user_id) of Feedback model.

@php
   
use App\Feedback;
use App\User;

$feedbacks = Feedback::all();
@endphp
<!DOCTYPE html>
<html>

<body>
<a href="/admin">ADMIN DASHBOARD</a> |<a href="{{ url('/logout') }}"> LOGOUT</a><br><br>
<h3>Feedbacks</h3>
<table border="1">
<tr><th>ID</th><th>Left By</th><th>Feedback</th></tr>
@foreach ($feedbacks as $feedback)
                
                <tr>
                <td>{{ $feedback->id}}</td>
                <td>{{ $user->name }}</td>
                <td>{{ $feedback->feedback }}</td>
                </tr>
$uid=$feedback->user_id;
$user= User::find($uid);

@endforeach
</table>
</body>
</html>

Upvotes: 2

Views: 1390

Answers (1)

thisiskelvin
thisiskelvin

Reputation: 4202

I would suggest creating a relation between feedback and user (If you don't have one already). Your relation would be put within the Feedback model and look like this:

// Feedback.php

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

This will relate the feedback to the user using the user_id on the feedback table.

After this, when calling feedback within your controller, you can then eager load the user relation with each feedback. This can be done within the following:

$feedbacks = Feedback::with('user')->get();

Finally, within your template, you will able to call the user through each feedback by doing the following:

{{ $feedback->user->name }}

Note: This example assumes name is a field on your user table.

Upvotes: 2

Related Questions