Last active
December 8, 2016 16:57
-
-
Save abler98/ee1b297fcfb8b0006e136ec8c5360e9d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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