Reputation: 199
User.php(User model)
class User extends Authenticatable
{
public function profiles(){
return $this->hasOne('App\Profile');
}
}
Profile.php (Profile model)
class Profile extends Model
{
public function users(){
return $this->belongsTo('App\User');
}
}
Function which returns data to view:
public function show_users(){
$users = User::where('id','!=',Auth::user()->id)->get();
return view('pages.show_users')->withUsers($users);
}
show_user.blade.php(View)
@foreach($users as $user)
{{$user->profile->first_name}} //Gives error:Trying to get property of non-object
{{$user->profiles['first_name']}} // Gives desired result
@endforeach
Why the result is returned in array instead of collection?
Upvotes: 0
Views: 854
Reputation: 7371
The reason that you are getting that error is beacause
Some users might not have a profile. so calling first_name on profile which is a null object will throw an error.
What you can is on php7 you can do
@foreach($users as $user)
{{$user->profiles->first_name ?? 'No first name'}}
@endforeach
php 5.6 and below
@foreach($users as $user)
@if($user->profiles->isNotEmpty())
{{$user->profiles->first_name}}
@else
No name
@endif
@endforeach
And moreover why don't use eager loading to load your profiles for performance benefit. Your query now will create the N+1 query problem.
You can change your query to
public function show_users()
{
$users = User::with('profiles')->where('id','!=',Auth::user()->id)->get();
return view('pages.show_users')->withUsers($users);
}
Hope it helps
Upvotes: 2
Reputation: 8750
The result returned is indeed a collection. It is just a typo issue
You forget an s
here in profiles
{{ $user->profiles->first_name }}
Also please note that even if you access first_name
as such
{{ $user->profiles['first_name'] }}
It doesn't mean it is not a collection.
If you check the source of Illuminate\Database\Eloquent\Model.php
, you will see that it implements some cool functions such as offsetGet
, offsetSet
, and offsetExists
More information here. PHP ArrayAccess
Upvotes: 1