Advertisement
multiarts

Save image with repository

Feb 4th, 2018
257
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.33 KB | None | 0 0
  1. // Controller
  2. public function store(ClientRequest $request, ClientRepositoryInterface $repository)
  3. {
  4.     $request->hasFile('image');
  5.     $file = $request->file('image');
  6.     $filename = \str_slug($request->get('name'),'-') . '.' . $file->getClientOriginalExtension();
  7.     $path = public_path('/uploads/clients/');
  8.     $url = '/uploads/clients/'.$filename;
  9.     $file->move($path, $filename);
  10.     $image = Image::make(sprintf($path.'%s', $filename))->resize(250, 100)->save();
  11.  
  12.     return $repository->create($request->all());
  13. }
  14.  
  15. // Repository
  16. <?php
  17.  
  18. namespace App\Repositories;
  19.  
  20. use Illuminate\Support\Facades\File;
  21. use Image;
  22.  
  23. class ImageRepository
  24. {
  25.     public function saveImage($image, $nameCli, $type, $size)
  26.     {
  27.         if (!is_null($image)) {
  28.             $file = $image;
  29.  
  30.             $extension = $image->getClientOriginalExtension();
  31.  
  32.             $fileName = \str_slug($nameCli, '-') .'.' . $extension;
  33.  
  34.             $destinationPath = public_path('uploads/'.$type.'/');
  35.  
  36.             $url = 'http://'.$_SERVER['HTTP_HOST'].'/uploads/'.$type.'/'.$fileName;
  37.  
  38.             $fullPath = $destinationPath.$fileName;
  39.  
  40.             $image = Image::make($file)
  41.                 ->resize($size, null, function ($constraint) {
  42.                   $constraint->aspectRatio();
  43.                 })
  44.                 ->encode('jpg');
  45.  
  46.             $image->save($fullPath, 100);
  47.  
  48.         } else {
  49.             return 'http://'.$_SERVER['HTTP_HOST'].'/uploads/'.$type.'/placeholder300x300.jpg';
  50.         }
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement