'fetching data through model binding relationship in laravel

I was trying to get the user's photo src which is stored in the photos table and the photo id is stored in the users' table. My code - I've written these lines in my User Model

Model - User

public function photo() {
    return $this->belongsTo(Photo::class);
}

and my code for printing the photo src -

Route::get("/photo",function() {
   
    $users = User::all();

    foreach($users as $user) {
        echo $user->photo->file . "<br>";
    }

});

It shows an error saying - Trying to get property 'file' of non-object

On the other hand, I have the same relationship binding which works fine - In the User Model -

public function role() {
    return $this->belongsTo(Role::class);
}

and for printing the role name of the user -

Route::get("/photo",function() {
    $users = User::all();
    foreach($users as $user) {
        echo $user->role->name . "<br>";
    }
});

so if the role name is printing by this way why the photo src is not printing



Solution 1:[1]

When you're using a Model relationship then you need to do it by calling it in your User::all()->with() method.

Whatever your relation may be it will be it's name will be called inside with() method in order to properly get the required data.

considering the relation ship is done properly you can do it like following:

Model User has the following relation with photos:

public function photo() {
    return $this->hasMany(Photo::class);
}

Model Photo has the following relation with User.

public function user(){ 
    return $this->belongsTo(User::class);
}

After this, you can call it inside your Controller

public function get_photo(){
  $users = User::all()->with('photo');
  return view('example.blade.php,compact('users'));
}

Routes

Route::get('/photo',[Controller::class,'get_photo'])->name('get.photo');

View

Your view can have the foreach loop to iterate through photos

foreach($users as $user) {
        echo $user->photo->file . "<br>";
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Hassaan Ali