I want to upload multiple images in Laravel with the error showing the filename into blade file. Like I want to upload say 4 files 2 of them are images and the other 2 are pdf, so it should stop me to do as I want just images to get uploaded and will also show me the two pdf's name which are not allowed. But what do I get is
The uploads.0 must be an image.
The uploads.0 must be a file of type: jpeg, png, jpg, gif, svg.
The uploads.2 must be an image.
The uploads.2 must be a file of type: jpeg, png, jpg, gif, svg.
so what do I want is that user must know that into which file they are making the mistake as there is the possibility of uploading more than 20 files, so if I can print the filename they can easily identify where is the problem, also I cannot get this error to be printed down the input, I got this error by using this code into my blade file,
@if (count($errors) > 0)
<div >
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
so I want that the validation should work with the filename and it should be shown below the input file as into my other input fields showing. Into my other input fields I have shown the errors with this for all errors
@if($errors->has('shipping_code'))
<div >{{ $errors->first('shipping_code') }}</div>
@endif
Into my controller
public function store(Request $request)
{
$validator = Validator::make($request->all(),[
'shipping_code' => 'required|string',
'customer_name' => 'required|exists:users,id',
'shipper_name' => 'nullable|exists:users,id',
'shipping_details' => 'nullable|string',
'pickup_date' => 'required|date',
'delivery_date' => 'nullable|date',
'driver_name' => 'required|exists:users,id',
'driver_fee' => 'required|regex:/^\d (\.\d{1,2})?$/',
'transaction_fee' => 'required|regex:/^\d (\.\d{1,2})?$/',
'remarks' => 'nullable|string',
'status' => 'required|in:0,1,2,3',
'uploads' => 'required',
'uploads.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
if ($validator->fails()) {
return redirect()->route('shipping.create')
->withErrors($validator)
->withInput();
}else{
DB::transaction(function () use($request) {
$exPd = explode(',',$request->driver_name);
$driver_id = $exPd[0];
$shipping = new Shipping();
$shipping->shipping_code = $request->shipping_code;
$shipping->customer_id = $request->customer_name;
$shipping->shipper_id = $request->shipper_name;
$shipping->driver_id = $driver_id;
$shipping->shipping_details = $request->shipping_details;
$shipping->pickup_date = convertDateToDB($request->pickup_date);
$shipping->delivery_date = convertDateToDB($request->delivery_date);
$shipping->driver_fee = $request->driver_fee;
$shipping->transaction_amount = $request->transaction_fee;
$shipping->remarks = $request->remarks;
$shipping->status = $request->status;
$shipping->created_at = date('Y-m-d H:i:s');
$shipping->created_by = Auth::user()->id;
$shipping->save();
if($request->hasfile('uploads')) {
foreach($request->file('uploads') as $file)
{
$input['imagename'] = time().'.'.$file->extension();
$filePath = public_path('/uploads/shipping_transaction_images/');
$img = Image::make($file->path());
$img->resize(110, 110, function ($const) {
$const->aspectRatio();
})->save($filePath.$input['imagename']);
$imgData[] = $input['imagename'];
$fileModal = new ShippingImage();
$fileModal->shipping_id = $shipping->id;
$fileModal->image_type = 'pickup';
$fileModal->image_file = $input['imagename'];
$fileModal->save();
}
}
});
return redirect()->route('shippings.index')
->with('success','Shipping Transaction Created Successfully');
}
}
CodePudding user response:
please check out this answer, maybe it can help, also it will not harm your DB::transaction
https://stackoverflow.com/a/73658905/12244217
You can do your validation like this
$messages = [];
if($request->hasfile('uploads')){
// dd($request->file('uploads'));
foreach ($request->file('uploads') as $key => $file) {
$messages['uploads.'.$key.'.image'] = 'The ' . $file->getClientOriginalName() . ' must be an image.';
$messages['uploads.' . $key . '.mimes'] = 'The ' . $file->getClientOriginalName() . ' must be a file of type: :values.';
}
}
$request->validate([
'shipping_code' => 'required|string',
'customer_name' => 'required|exists:users,id',
'shipper_name' => 'nullable|exists:users,id',
'shipping_details' => 'nullable|string',
'pickup_date' => 'required|date',
'delivery_date' => 'nullable|date',
'driver_name' => 'required|exists:users,id',
'driver_fee' => 'required|regex:/^\d (\.\d{1,2})?$/',
'transaction_fee' => 'required|regex:/^\d (\.\d{1,2})?$/',
'remarks' => 'nullable|string',
'status' => 'required|in:0,1,2,3',
'uploads' => 'required|array',
'uploads.*' => 'image|mimes:jpg,jpeg,png'
], $messages);
You can fetch error for other fields like the way you have used
@if($errors->has('shipping_code'))
<div >{{ $errors->first('shipping_code') }}</div>
@endif
But for uploads you can use For getting if no file selected
@if ($errors->has('uploads'))
<div >
<strong>{{ $errors->first('uploads') }}</strong>
</div>
@endif
If multiple selected files have error
@if($errors->has('uploads.*'))
@foreach ($errors->get('uploads.*') as $message)
@foreach ( $message as $value)
<div >{{ $value }}</div>
@endforeach
@endforeach
@endif
CodePudding user response:
<!doctype html>
<html lang="{{ app()->getLocale() }}">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel Uploading</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css?family=Raleway:100,600" rel="stylesheet" type="text/css">
<!-- Styles -->
<style>
.container {
margin-top:2%;
}
</style>
</head>
<body>
@if (count($errors) > 0)
<div >
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<div >
<div >
<div > <img src="/32114.svg" width="80" /></div>
<div ><h2>Laravel Multiple File Uploading With Bootstrap Form</h2>
</div>
</div>
<br>
<div >
<div ></div>
<div >
<form action="/multiuploads" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
<div >
<label for="Product Name">Product Name</label>
<input type="text" name="name" placeholder="Product Name" >
</div>
<label for="Product Name">Product photos (can attach more than one):</label>
<br />
<input type="file" name="photos[]" multiple />
<br /><br />
<input type="submit" value="Upload" />
</form>
</div>
</div>
</div>
</body>
</html>
// controller code
<?php
namespace App\Http\Controllers;
use App\Item;
use App\ItemDetail;
use Illuminate\Http\Request;
class UploadController extends Controller
{
public function uploadForm()
{
return view('upload_form');
}
public function uploadSubmit(Request $request)
{
$this->validate($request, [
'name' => 'required',
'photos'=>'required',
]);
if($request->hasFile('photos'))
{
$allowedfileExtension=['pdf','jpg','png','docx'];
$files = $request->file('photos');
foreach($files as $file){
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$check=in_array($extension,$allowedfileExtension);
//dd($check);
if($check)
{
$items= Item::create($request->all());
foreach ($request->photos as $photo) {
$filename = $photo->store('photos');
ItemDetail::create([
'item_id' => $items->id,
'filename' => $filename
]);
}
echo "Upload Successfully";
}
else
{
echo '<div ><strong>Warning!</strong> Sorry Only Upload png , jpg , doc</div>';
}
}
}
}
}?>
//file storing code
return [
'default' => 'local',
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
],