Attempt to read property "name" on null LARAVEL 8

  eloquent, laravel, orm, relationship

I have the following problem.
It turns out that I want to access a relation of a model, or rather an attribute of a User relation with the model itself that I’m manipulating, but it throws me the error: Attempt to read property "name" on null. I show you my code.

Image model

<?php

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;

class Image extends Model
{
    protected $table = 'images';

    public function comments(){
        return $this->hasMany(Coment::class);
    }

    public function like(){
        return $this->hasMany(Like::class);
    }

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

web.php // archive of routes

Route::get('/', function () {

    $images = Image::all();
    foreach($images as $image){
        echo $image->imagen_path. "<br/>";
        echo $image->description. "<br/>";
        echo $image->user->name." ".$image->user->surname;
        die();
        if(count($image->comments) >= 1){
            echo "<h4>Comentarios</h4>";
            foreach($image->comments as $comment){
                $comment->user->name. " " .$comment->user->surname.":";
                $comment->content. "<br/>";
            }
        }
        echo "<hr/>";
    }

    die();
    return view('welcome');
});

The question is why it does not allow me to enter the name attribute of the user object. I am in laravel 8

Source: Laravel

Leave a Reply