Here's my current issue.
At the moment, I have a page with elements that can be added in and appended via AJAX. These elements contain forms, image uploads etc.
I have a middleware on my entire application that checks the size of any image being uploaded at any given time and makes sure its under 5MB (image validation for each image upload on the application is not an option, it has to be 1 controller that maintains all image upload validation).
If the request detects an image thats over 5MB, it will run this code
return redirect()->back()->withInput($request->all())->withErrors(array('Image' => 'Sorry, ' . $file->getClientOriginalName() . ' is too large, maximum file size is 5MB. Please reduce the size of your image!'));
This code is very temperamental, and heres why.
I need the page to be in the EXACT same state i left it in, when its returned. That means all AJAX loaded elements, all images, everything needs to be in the same state, so redirect()->back()->withInput($request->all())
doesn't work, because it still refreshes the page and removes everything loaded appended and added in that instance.
I need to be able to cancel the request if it fails.
In plain english, When this middleware is ran, detect all images. If there is an image that is over 5MB, do not refresh the page or anything. Just error
I know this seems silly, because the request cannot pass something back without refreshing, but I thought id ask / open to suggestions.
Here's my middleware
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\UploadedFile;
use Symfony\Component\HttpFoundation\Response;
class ImageInterceptor
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
foreach (array_filter(array_flatten($request->files->all())) as $file) {
//Check if the file being uploaded is not a csv
if($file->getClientOriginalExtension() != 'csv'){
$filename = $file->getClientOriginalName();
$size = $file->getClientSize(); // size in bytes!
$onemb = pow(1024, 2);
if ($size > $onemb * 5) {
//Return back, image is too big!
return redirect()->back()->withInput($request->all())->withErrors(array('Image' => 'Sorry, ' . $file->getClientOriginalName() . ' is too large, maximum file size is 5MB. Please reduce the size of your image!'));
}
}
}
return $next($request);
}
}