Skip to content

Instantly share code, notes, and snippets.

@abler98
Last active December 8, 2016 16:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abler98/ee1b297fcfb8b0006e136ec8c5360e9d to your computer and use it in GitHub Desktop.
Save abler98/ee1b297fcfb8b0006e136ec8c5360e9d to your computer and use it in GitHub Desktop.
<?php
namespace App\Models;
use Illuminate\Http\Exception\HttpResponseException;
use Illuminate\Http\UploadedFile;
use Intervention\Image\Constraint;
use Intervention\Image\Exception\NotWritableException;
class Photo extends \Eloquent
{
const THUMB_SIZE = 300;
protected $fillable = ['client_name', 'name'];
protected $hidden = ['id', 'created_at', 'updated_at'];
protected $appends = ['src'];
/**
* Обработка загруженного изображения
*
* @param UploadedFile $file
* @param bool $save
* @return static
*/
public static function fromUploadedFile(UploadedFile $file, bool $save = true)
{
/** @var Photo $photo */
$photo = self::firstOrNew([
'client_name' => $file->getClientOriginalName(),
'name' => $file->hashName(),
]);
if (!($path = $file->storeAs('photos', $photo->name, 'public'))) {
throw new HttpResponseException(
response()->error('Ошибка загрузки изображения #1')
);
}
$thumb = \Image::make($path);
$thumb->resize(null, self::THUMB_SIZE, function (Constraint $constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
try {
$thumb->save(
storage_path(sprintf('app/public/photos/thumbs/%s', $photo->name))
);
} catch (NotWritableException $e) {
throw new HttpResponseException(
response()->error('Ошибка загрузки изображения #2')
);
}
if ($save) $photo->save();
return $photo;
}
/**
* Ссылка на изображение
*
* @return string
*/
public function getSrcAttribute()
{
return asset(sprintf('storage/photos/%s', $this->name));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment