I have four tables:
places
with columns: id
place_details
with columns: id, place _id
photos
with columns: id
place_photos
with columns: id, place_id, photo_id
Inside the Photo
model I have:
class Photo extends Model
{
use HasFactory;
protected $table = 'photos';
protected $appends = array(
'storage_url',
);
public function getStorageUrlAttribute()
{
$path = 'photos/' . $this->id . '.jpg';
if (Storage::disk('public')->exists($path))
{
return Storage::disk('public')->url($path);
}
return null;
}
}
I need to be able to access the Place id
in the getStorageUrlAttribute function. How can I do this?
Here is what my PlaceDetail
model looks like:
class PlaceDetails extends Model
{
use HasFactory;
protected $table = 'place_details';
protected $with = [
'photo',
];
public function place(): BelongsTo
{
return $this->belongsTo(Place::class);
}
public function photo(): HasOneThrough
{
return $this->hasOneThrough(
Photo::class,
PlacePhoto::class,
'place_id', // Foreign key on PlacePhoto table
'id', // Foreign key on Photo table
'place_id', // Local key on PlaceDetail table
'photo_id' // Local key on PlacePhoto table
)->where('is_primary', true);
}
And here is what my Place
model looks like:
class Place extends Model
{
use HasFactory;
protected $table = 'places';
protected $with = [
'details',
];
public function details(): HasOne
{
return $this->hasOne(PlaceDetails::class);
}
}