0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Laravel サービスへの切り離しについて

Posted at

サービスへの切り離し→重複を防ぎ、ファットコントローラを防ぐ

関数みたいにして、処理を別のファイルから読み込むイメージ

Reactとかやってる場合はコンポーネントと考えが似てるかも。。。

とりあえずやってみる

今回は、ファイルアップロード機能をいろんなところで使いたいのでそれを切り離す

  1. app直下に「Services」フォルダを作成  (大抵の場合フォルダ名を「Services」にするといい)
  2. 今回の場合は「ImageService.php」ファイルを作成 (App\Services\ImageService.php)
  3. 渡す引数(今回は、$imageFile,$folderName)に注意しながらコードを持ってくる
<?php
namespace App\Services;
use Illuminate\Support\Facades\Storage;
use InterventionImage;

class ImageService
{
  public static function upload($imageFile,$folderName){

    $fileName = uniqid(rand().'_');
    $extension = $imageFile->extension();
    $fileNameToStore = $fileName. '.' . $extension;
    $resizedImage = InterventionImage::make($imageFile)->resize(1920, 1080)->encode();

    Storage::put('public/' . $folderName . '/' . $fileNameToStore, $resizedImage );

    return $fileNameToStore;
  }

}

4.読み込む

 use App\Services\ImageService;//これがないと使えない


 public function update(UploadImageRequest $request, $id){
        $imageFile = $request->image; //PC側に一時保存 
        if(!is_null($imageFile) && $imageFile->isValid() ){
            $fileNameToStore = ImageService::upload($imageFile, 'shops');//ここで読み込み
        }
        return redirect()->route('owner.shops.index');
    }
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?