kaiserkais's avatar

Trying to get property of non-object

i try to call an image from database and i get this

this is what i have in user model

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

and photo class

protected $fillable = ['file'];

protected $uploads = '/images/';


// function with laravel
public function getFileAttribute($photo) {
    
    return $this->uploads . $photo;
    
}

when icall wth this

public function show($id) { //

    $user = User::findOrFail($id);
    

    return view('layouts.users.profile', compact('user'));
}

{{$user->photo->file }}

iget this message

Trying to get property of non-object

0 likes
2 replies
click's avatar
click
Best Answer
Level 35

Your $user does not return a \App\Photo model. So if you do dd($user->photo) you will probably see null on your screen.

Does the user you are trying to view at this moment have a photo attached to it? Take a look in you database table user or do: dd($user->photo_id)

Relationship

I think you use the wrong relationship here. How does your database look like?

Does your user table have a column named photo_id? Or does your photo table have a column named user_id?

If the last is the case you should use hasOne() relation instead of the belongsTo() on the User model. See for more examples the documentation on one-to-one relationships. https://laravel.com/docs/5.5/eloquent-relationships#one-to-one

App/User

public function photo()
{
    return $this->hasOne('App\Photo');
}

App/Photo

public function user()
{
   return $this->belongsTo('App\User');
}
1 like
kaiserkais's avatar

@m-rk oh this is why... this user that i try to fetch not attached to a photo thank you friend this is a beginner mistake ...im beginner ....thankyou

Please or to participate in this conversation.