Skip to content

Commit

Permalink
feat: add image to items variant
Browse files Browse the repository at this point in the history
  • Loading branch information
phojie committed Dec 4, 2022
1 parent 2017b2b commit 744da7a
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 20 deletions.
1 change: 1 addition & 0 deletions app/Http/Resources/VariantResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ public function toArray($request): array
'status' => $this->status,
'stock' => $this->stock,
'price' => $this->price,
'image' => $this->image,
'color' => $this->color,
'createdAt' => $this->created_at,
'updatedAt' => $this->updated_at,
Expand Down
65 changes: 45 additions & 20 deletions app/Models/Variant.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,27 +5,52 @@
use App\Services\MiscServices;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Database\Eloquent\Model;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
use Spatie\MediaLibrary\MediaCollections\Models\Media;

class Variant extends Model
class Variant extends Model implements HasMedia
{
use HasFactory;
use HasUuids;

public $fillable = [
'name',
'status',
'stock',
'price',
'item_id',
];

public static function boot(): void
{
parent::boot();
self::creating(function ($model) {
$model->color = (new MiscServices())->getRandomColor();
});
}
use HasFactory;
use HasUuids;
use InteractsWithMedia;

public $fillable = [
'name',
'status',
'stock',
'price',
'item_id',
];

protected $appends = [
'image',
];

public function getImageAttribute(): string
{
return $this->getFirstMediaUrl('image', 'thumb') ?: 'https://robohash.org/'.$this->id.'?set=set1&bgset=bg2&size=400x400';
}

public function registerMediaCollections(): void
{
$this->addMediaCollection('image')
->singleFile();
}

public function registerMediaConversions(Media $media = null): void
{
$this->addMediaConversion('image')
->width(400)
->height(400);
}

public static function boot(): void
{
parent::boot();
self::creating(function ($model) {
$model->color = (new MiscServices())->getRandomColor();
});
}
}

0 comments on commit 744da7a

Please sign in to comment.