exchange/app/Models/News.php

78 lines
2.8 KiB
PHP
Raw Normal View History

2022-11-28 19:17:00 +00:00
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Backpack\CRUD\app\Models\Traits\SpatieTranslatable\HasTranslations;
use Illuminate\Support\Str;
use Intervention\Image\ImageManagerStatic as Image;
class News extends Model
{
use \Backpack\CRUD\app\Models\Traits\CrudTrait;
use HasFactory;
use HasTranslations;
protected $guarded = [''];
public $translatable = ['title', 'short_description', 'description'];
public static function boot()
{
parent::boot();
static::deleted(function($obj) {
2022-12-02 14:20:12 +00:00
\Storage::disk('uploads')->delete($obj->image);
2022-11-28 19:17:00 +00:00
});
}
public function setImageAttribute($value)
{
$attribute_name = "image";
// or use your own disk, defined in config/filesystems.php
$disk = config('backpack.base.root_disk_name');
// destination path relative to the disk above
$destination_path = "public/uploads/news";
// if the image was erased
if (empty($value)) {
// delete the image from disk
if (isset($this->{$attribute_name}) && !empty($this->{$attribute_name})) {
\Storage::disk($disk)->delete($this->{$attribute_name});
}
// set null on database column
$this->attributes[$attribute_name] = null;
}
// if a base64 was sent, store it in the db
if (Str::startsWith($value, 'data:image'))
{
// 0. Make the image
$image = \Image::make($value)->encode('jpg', 90);
// 1. Generate a filename.
$filename = md5($value.time()).'.jpg';
// 2. Store the image on disk.
\Storage::disk($disk)->put($destination_path.'/'.$filename, $image->stream());
// 3. Delete the previous image, if there was one.
if (isset($this->{$attribute_name}) && !empty($this->{$attribute_name})) {
\Storage::disk($disk)->delete($this->{$attribute_name});
}
// 4. Save the public path to the database
// but first, remove "public/" from the path, since we're pointing to it
// from the root folder; that way, what gets saved in the db
// is the public URL (everything that comes after the domain name)
$public_destination_path = Str::replaceFirst('public/', '', $destination_path);
$this->attributes[$attribute_name] = $public_destination_path.'/'.$filename;
// TODO
// crop image to 300x300
} elseif (!empty($value)) {
// if value isn't empty, but it's not an image, assume it's the model value for that attribute.
$this->attributes[$attribute_name] = $this->{$attribute_name};
}
}
}