Home > Mobile >  Property [file] does not exist on this collection instance Laravel
Property [file] does not exist on this collection instance Laravel

Time:05-31

I have three tables('users,cars and photos').

users table

enter image description here

photos table

enter image description here

I want to display the newest image file for user avatar picture. In this case I want to show as profile avatar photo with id = 2 because it's the latest photo for the user(id=1) because of imageable_id=1 and because imageable_type is for User(for user avatar). App\Models\Car belongs to cars and I don't need that for now.

Summary: Want to display the newest photo for the user avatar.

I Am using this code below inside my blade file:

<img src="{{$detected_user->photo->file}}" alt="">

In Controller I use $detected_user to authenticate user which is logged in and I use '->photo'(relationship inside my model). '->file' is the name of the column inside my 'photos' table.

User Model

public function photo() {
    return $this->morphMany('App\Models\Photo', 'imageable');
}

Cars Model

public function photo() {
    return $this->morphMany('App\Models\Photo', 'imageable');
}

Photo Model

public function imageable() {
    return $this->morphTo();
}

CodePudding user response:

On the User model you can define two relationships

//App\Models\User.php

public function photos()
{
    return $this->morphMany('App\Models\Photo', 'imageable');
}

public function latest_photo()
{
    return $this->morphOne('App\Models\Photo', 'imageable')->latest('id');
}

In the view

<img src="{{$detected_user->latest_photo->file}}" alt="">

And similarly for the Car model

//App\Models\Car.php

public function photos()
{
    return $this->morphMany('App\Models\Photo', 'imageable');
}

public function latest_photo()
{
    return $this->morphOne('App\Models\Photo', 'imageable')->latest('id');
}
  • Related