DEV Community

Cover image for Install and Run Image Intervention in Laravel
Raymond Baghumian
Raymond Baghumian

Posted on • Updated on

Install and Run Image Intervention in Laravel

When presenting version 3, the Image Intervention package has seen many changes. codes from version 2 are not compatible with version 3 and need to be changed.

OK.

  • Install Package Image Intervention :
composer require intervention/image
Enter fullscreen mode Exit fullscreen mode
  • in users table, create image field :
$table->string('image')->nullable();
Enter fullscreen mode Exit fullscreen mode
  • Creating Field image :
<div class="col-12">
    <label for="input8" class="form-label">Upload image</label>
    <input type="file" name="image" class="form-control rounded-5 @error('image') is-invalid @enderror" id="input8">
    @error('image')
       <span class="invalid-feedback" role="alert">
          <strong>{{ $message }}</strong>
       </span>
    @enderror
</div>
Enter fullscreen mode Exit fullscreen mode
  • in windows, enable imagick.so xampp extension. in linux Enter the following commands :
sudo apt install php-imagick
php -m | grep imagick
sudo systemctl restart apache2
Enter fullscreen mode Exit fullscreen mode
  • Creating Function saveImage in User.php :
use Intervention\Image\ImageManager;

public static function saveImage($file)
{
        if ($file){
            $name = $file->hashName();

            $smallImage = ImageManager::imagick()->read($file->getRealPath());
            $bigImage = ImageManager::imagick()->read($file->getRealPath());
            $smallImage->resize(256, 256, function ($constraint){
                $constraint->aspectRatio();
            });

            Storage::disk('local')->put('users/small/'.$name, (string) $smallImage->encodeByMediaType('image/jpeg', 90));
            Storage::disk('local')->put('users/big/'.$name, (string) $bigImage->encodeByMediaType('image/jpeg', 90));

            return $name;

        }else{
            return "";
        }
}
Enter fullscreen mode Exit fullscreen mode
  • Function Store in UserController.php :
public function store(Request $request)
{
        $image = User::saveImage($request->image);

        User::query()->create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password),
            'image' => $image,
        ]);

        return to_route('users.index');
}
Enter fullscreen mode Exit fullscreen mode
  • in config/filesystem.php Enter the following codes :
'local' => 
[
   'driver' => 'local',
   'root' => public_path('images'),
   'throw' => false,
],
Enter fullscreen mode Exit fullscreen mode
  • Show user's image :
@foreach($users as $index=>$row)
<figure>
       <img src="{{asset('images/users/small/' .$row->image)}}" class="rounded-4" width="52px">
</figure>
@endforeach
Enter fullscreen mode Exit fullscreen mode

Good luck. :)

Top comments (0)