/** * Handles the command execution. * * @param UploadImage $command * @return null|string */ public function handle(UploadImage $command) { if ($command->postId) { // load the Post for this image $post = $this->posts->findOrFail($command->postId, $command->actor); } else { $post = null; } // todo check rights // todo validate file $image = new Image(); $image->user_id = $command->actor->id; $image->upload_method = 'local'; if ($post) { $image->post_id = $post->id; } $this->events->fire(new ImageWillBeSaved($post, $command->actor, $image, $command->file)); $file_name = sprintf('%d-%d-%s.jpg', $post ? $post->id : 0, $command->actor->id, str_random()); if (!$this->uploadDir->write($file_name, $command->file)) { // todo should throw error return null; } $appPath = parse_url($this->app->url(), PHP_URL_PATH); $image->file_name = sprintf('%s/assets/images/%s', $appPath, $file_name); $image->created_at = Carbon::now(); $image->save(); return $image; }
public static function boot() { Image::deleted(function ($image) { // todo trigger service to delete image // for instance from local storage }); }
/** * Deletes any images that were listed for that post. * * @param PostWasDeleted $event */ public function postWasDeleted(PostWasDeleted $event) { Image::where('post_id', $event->post->id)->delete(); }