Created
September 13, 2015 18:59
-
-
Save amodef/1931f0908242703b1efd to your computer and use it in GitHub Desktop.
Project Flyer
This file contains 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; | |
use Image; | |
use Illuminate\Database\Eloquent\Model; | |
use Symfony\Component\HttpFoundation\File\UploadedFile; | |
class Photo extends Model | |
{ | |
protected $table = 'flyer_photos'; | |
protected $fillable = ['name', 'path', 'thumbnail_path']; | |
protected $file; | |
protected $name; | |
protected static function boot() | |
{ | |
static::creating(function ($photo) { | |
return $photo->upload(); | |
}); | |
} | |
/** | |
* A photo belongs to a flyer. | |
* | |
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo | |
*/ | |
public function flyer() | |
{ | |
return $this->belongsTo('App\Flyer'); | |
} | |
public static function fromFile(UploadedFile $file) | |
{ | |
$photo = new static; | |
$photo->file = $file; | |
$photo->fill([ | |
'name' => $photo->setName(), | |
'path' => $photo->filePath(), | |
'thumbnail_path' => $photo->thumbnailPath(), | |
]); | |
return $photo; | |
} | |
protected function setName() | |
{ | |
$hash = sha1( | |
time() . $this->file->getClientOriginalName() | |
); | |
$extension = $this->file->getClientOriginalExtension(); | |
return $this->name = "{$hash}.{$extension}"; | |
} | |
public function filePath() | |
{ | |
return $this->baseDir() . '/' . $this->name; | |
} | |
public function thumbnailPath() | |
{ | |
return $this->baseDir() . '/tn-' . $this->name; | |
} | |
public function baseDir() | |
{ | |
return 'images/photos'; | |
} | |
public function upload() | |
{ | |
$this->file->move($this->baseDir(), $this->name); | |
$this->makeThumbnail(); | |
return $this; | |
} | |
public function makeThumbnail() | |
{ | |
Image::make($this->filePath()) | |
->fit(200) | |
->save($this->thumbnailPath()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment