Laravel: get name from table users
Clash Royale CLAN TAG#URR8PPP
Laravel: get name from table users
I need get the name field in user table
My method in the controller:
public function reviewsactivity()
$activity = Activity::orderBy('id', 'DESC')->paginate();
$users = User::orderBy('id', 'ASC')->pluck('id', 'name');
return view('reviews.reviewsactivity', compact('activity', 'users'));
And the view:
@foreach($activity as $actividad)
<tr>
<td> $actividad->description </td>
<td> $actividad->subject_type </td>
<td> $actividad->user->name </td>
<td> $actividad->causer_type </td>
<td> date('d-m-Y', strtotime($actividad->created_at)) </td>
</tr>
@endforeach
The field in the Activity table: causer_id
And I have the next log:
Trying to get property of non-object
(View: C:laragonwwwtaoresourcesviewsreviewsreviewsactivity.blade.php)
Activity
User
use Relationship for this. if each activity has a user, use belongsTo relationship.
– Ali Özen
Aug 10 at 15:38
2 Answers
2
Assuming you have user_id
in activities
table referencing users
table then you can define belongsTo
relationship in Activity
model
user_id
activities
users
belongsTo
Activity
Activity Model
public function user()
return $this->belongsTo(User::class, 'user_id');
Now Fetch Activity with eager loading using with('user')
with('user')
public function reviewsactivity()
$activity = Activity::with('user')->orderBy('id', 'DESC')->paginate();
$users = User::orderBy('id', 'ASC')->pluck('id', 'name');
return view('reviews.reviewsactivity', compact('activity', 'users'));
Check Eager Loading documents here https://laravel.com/docs/5.6/eloquent-relationships#eager-loading
You need to check if the activity has an attached user or not first:
<td> !is_null($actividad->user)?$actividad->user->name:'' </td>
Else you're trying to get the attribute name
from a non-object null
that why you're getting the message error.
name
null
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
do you have relation between
Activity
andUser
models ?– rkj
Aug 10 at 15:38