Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect Image upload on Laravel through middleware

I'm looking at being able to have a image detect in a global middleware on Laravel.

My goal is to make the middleware, detect if there is currently an image being uploaded, and then detect its size and manipulate it.

Is this possible?

I've inherited a project, and need to manipulate every global image upload, but there are far too many individual scripts to change them all separately, I need some sort of way to change them all globally.

I'm open to suggestions!

like image 648
S_R Avatar asked Sep 16 '25 06:09

S_R


1 Answers

<?php

namespace App\Http\Middleware;

use Closure;
use Symfony\Component\HttpFoundation\Response;

class ImageInterceptorMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        foreach (array_flatten($request->files->all()) as $file) {
            $size = $file->getClientSize(); // size in bytes!

            $onemb = pow(1024, 2); // https://stackoverflow.com/a/2510446/6056864

            if ($size > $onemb) {
                abort(Response::HTTP_UNPROCESSABLE_ENTITY);
            }
        }

        return $next($request);
    }
}
like image 154
Quezler Avatar answered Sep 19 '25 04:09

Quezler