Home > Software engineering >  Attempt to read property "file" on null
Attempt to read property "file" on null

Time:04-09

I keep getting the file on null error and can't seem to find why he can't locate the file?

        @foreach($users as $user)
            <tr>
                <td>
                   <img height="62" src="{{asset($user->userdetail->file)}}" alt="">

                </td>
            </tr>
        @endforeach

Userdetail Model

class UserDetail extends Model
{
    use HasFactory;
    protected $fillable = ['file'];
    protected $uploads = '/img/avatar/';

    public function getFileAttribute($userdetail){
        return $this->uploads . $userdetail;
    }
}

user model

    protected $fillable = [
        'name',
        'is_active',
        'email',
        'photo_id',
        'password',
    ];

    public function userdetail(){
        return $this->belongsTo(UserDetail::class);
    }

Location of file enter image description here

Migration userdetails

    public function up()
    {
        Schema::create('user_details', function (Blueprint $table) {
            $table->id();
            $table->string('file');
            $table->timestamps();
        });
    }

enter image description here user enter image description here

ddump of $user

enter image description here

CodePudding user response:

You have to create the relationship for photo. make this function in user model and place the name of the correct model

public function photo(){ return $this->hasOne(UserDetails::class, 'id', 'photo_id'); }

CodePudding user response:

The problem was not the relation.

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

my problem was the name of the function i named it userdetail and then it will look for userdetail_id instead i needed it to name photo because then it will look for photo_id

Now it works!

  • Related