How to fix incomplete multiple image uploads - laravel

I have problem with uploading multiple images. The did successfully upload multiple images, but not every image was uploaded. Here is my form
{!! Form::open(['files'=>true,'url'=>'upload/file'])!!}
{!! Form::file('file[]',['multiple'=>'multiple']) !!}
{!! Form::submit('save') !!}
{!! Form::close() !!}
I tried to upload the specific type of images in my validation.
public function upload()
{
$this->validate(request(),['file.*'=>'required|image|mimes:jpg,jpeg,png']);
$files = request()->file('file');
foreach ($files as $file) {
$ext = $file->getClientOriginalExtension();
$file->move(public_path('uploads'),'image_'.time().'.'.$ext);
}
return back();
}
Sometimes it uploaded multiple images, but not all of the images were uploaded.

the problem is that:
i can't use time() because i upload these files at the same time
i used
Str::random(50)
instead

Related

I want to use images of products that I register in the database - Laravel

I programmed a product registration. The registration for the database is working correctly. My problem is that I can't show the images that I registered in the database. I created an imput where the name of the image is inserted. This name is saved in the database and the image is saved with the same name, however it is saval in public. The images are inside the public / storage / products folder.
Controller:
public function index()
{
$products = Product::paginate(10);
return view('products.index', [
'products' => $products,
]);
}
public function store(Request $request)
{
// Create registration
$data = $request->only('name', 'price', 'imageName');
Product::create($data);
// Image
if($request->file('imageProduct')->isValid()){
$nameFile = $request->imageName . '.' . $request->file('imageProduct')->getClientOriginalExtension();
$request->file('imageProduct')->storeAs('products', $nameFile);
return redirect()->route('ProductControllerIndex');
}
}
view:
<div>
#foreach ($products as $product)
<p>
Id: {{ $product->id }}
</p>
<p>
Nome do produto: {{ $product->name }}
</p>
<p>
Preço: {{ $product->price }}
</p>
<p>
{{ $product->imageName }}
</p>
<p>
<img src="{{ asset('storage/products/'.$product->imageName) }}" alt="">
</p>
<hr>
#endforeach
</div>
The core issue here is that your Image's extension is not being saved to the database, so $product->imageName, when used in the asset() helper, doesn't generate a complete URL for the image. You'll need to refactor your code a little to get it to save:
public function store(Request $request) {
$nameFile = $request->input('imageName', '');
if($request->file('imageProduct')->isValid()){
$nameFile .= '.' . $request->file('imageProduct')->getClientOriginalExtension();
$request->file('imageProduct')->storeAs('products', $nameFile);
}
$request->merge(['imageName' => $nameFile]);
$data = $request->only('name', 'price', 'imageName');
Product::create($data);
return redirect()->route('ProductControllerIndex');
}
In the above code, the value for $nameFile is defaulted to the value in $request->input('imageName'), or an empty string '' if nothing is supplied. Next, if a valid image is uploaded, the $nameFile variable is appended with the extension. Lastly, the $request variable is updated with the name value for imageName. The remainder of the code creates the new Product with the data supplied (using the ->only() modifier) and redirect as required.
The rest of your code should be ok, as long as the file exists in the correct directory after ->storeAs() and the fully-qualified image name is saved to the database.
Note: If for whatever reason Product::create() doesn't work with this approach, you can use the new Product() ... $product->save() approach: (there might be an issue with $request->merge() using an existing key, as I can't actually test that)
$product = new Product();
$product->name = $request->input('name');
$product->price = $request->input('price');
$product->imageName = $fileName;
$product->save();

Uploading files with infyom generator

I am trying to upload a file with laravel using the code generated by the infyom generator. The file seems to be uploaded but this is what is shown on the application when I view the report (C:\xampp\tmp\php7925.tmp). Provided below is the code for my application.
Thank you so much and really appreciate the help in this project.
rgds,
Form
<!-- Inf File Field -->
<div class="form-group col-sm-6">
{!! Form::label('inf_file', 'Attachments:') !!}
{!! Form::file('inf_file') !!}
</div>
Controller
{
$input = $request->all();
$infrastructure = $this->infrastructureRepository->create($input);
$file = $request->file('inf_file');
$file = $request->inf_file;
if ($request->hasFile('inf_file')){
//
if ($request->file('inf_file')->isValid()){
}
}
Flash::success('Infrastructure saved successfully.');
return redirect(route('infrastructures.index'));
}
This is how you display when you view your records,
<!-- Inf File Field -->
<div class="form-group">
{!! Form::label('inf_file', 'Attachements:') !!}
<a download href="{{ asset($infrastructure->inf_file) }}">Download</a>
</div>
Managed to solve it.
public function store(CreateinfrastructureRequest $request)
{
$input = $request->all();
if ($request->hasFile('inf_file')){
//Validate the uploaded file
$Validation = $request->validate([
'inf_file' => 'required|file|mimes:pdf|max:30000'
]);
// cache the file
$file = $Validation['inf_file'];
// generate a new filename. getClientOriginalExtension() for the file extension
$filename = 'Infras-' . time() . '.' . $file->getClientOriginalExtension();
// save to storage/app/infrastructure as the new $filename
$InfrasFileName = $file->storeAs('infrastructure', $filename);
$path = "/storage/app/public/".$InfrasFileName;
}
$input['inf_file'] = $path;
$infrastructure = $this->infrastructureRepository->create($input);
Flash::success('Infrastructure saved successfully. ' . $path);
return redirect(route('infrastructures.index'));
}

The "" file does not exist or is not readable

I am having some issue while trying to upload multiple images on the back end in Laravel. I have a simple form with an input field and a multiple attribute that should upload an array of images in the database but whatever I try, I get the same error 'The "" file does not exist or is not readable'. I checked the names in the input field and they are the same as the name in the file() method. Any help is appreciated.
PS: Am a newbie to Laravel and PHP...
ProductController:
foreach($request->file('images')->store('images') as $images) {
$product->images()->create([
'images' => $images
]);
}
Blade file:
<form method="POST" enctype="multipart/form-data">
#csrf
<h5>Upload Multiple Images</h5>
<input type="file" multiple name="images" id="images"> Upload Images
</form
I know this is an old question, but I had the same issue a few days ago. Hope this helps anyone.
I solved the problem by setting php_value upload_max_filesize in php.ini over the size of my uploaded file.
This is where I found the answer in case you are interested:
If someone else gets this error and it doesn't turn out to be a permissions issue, check your php.ini...make sure that your upload_max_filesize is as big as your post_max_size. I had 1000M for post_max_size (we deal with some big ol' video files), but only 100M for upload_max_size (I blame my old eyes). The upload would churn for a long time, and then throw the error above.
https://github.com/laravel/framework/issues/31249
Try..
$input = $request->all();
$datas = [];
if ($request->hasfile('images')) {
foreach ($request->file('images') as $key => $file) {
$name = $file->getClientOriginalName();
$file->move(public_path() . '/your path /', $name); //if you want to store image in yopur folder
$datas[$key] = $name;
$file = new YourMOdelNAme();
foreach ($datas as $data) {
$file->images = $data;
$file->save();
}
}
}
name images array
<form method="POST" enctype="multipart/form-data">
#csrf
<h5>Upload Multiple Images</h5>
<input type="file" multiple name="images[]" id="images"> Upload Images
</form
Upload files using below code
$files = $request->file('images');
if($request->hasFile('images'))
{
foreach ($files as $file)
$product->images()->create([
'images' => $file
]);
}

Laravel 5.8 image failed to upload

I cannot seem to upload an image file with Laravel. I keep getting the photo failed to upload.
My form:
<form id="save_report_form" action="{{ route('report.add') }}" method="post" enctype="multipart/form-data">
<input type="file" name="image" class="upload-photo" id="image" accept="image/png,image/jpg" />
</form>
My Controller:
public function add(Request $request)
{
$this->validate($request, [
'image' => 'required|image|mimes:png,jpg',
]);
// Get all file details and store in public
$disk = Storage::disk('public');
$file = $request->file('image');
$ext = $file->getClientOriginalExtension();
$filename = $file . '.' . $ext;
$disk->put($filename, file_get_contents($file), 'public');
return redirect()->back();
}
I have changed upload_max_filesize to 20mb for my dev server.
Where can I look to find the reason for the upload failure? I am not getting anything in the Laravel log. What have I missed. Thanks.
can you replace
$filename = $file . '.' . $ext;
with
$filename = $request->image->getClientOriginalName();
You can check what is the result of $filename with dd() /dd($filename) function and see if it is what you expect. If it is not, probably there is the problem.
Also as far as i see in the official docs(https://laravel.com/docs/5.8/filesystem#file-visibility) the usage of put() method is exampled without php native file_get_contents(check this also).

How to pass id to controller in laravel 5.2

I using this method to upload the image and passing the page id so i can store the path into database but having error "Missing argument 2 for App\Http\Controllers\RoundtablesController::postImage()"
This is my form
<div class="btn-group">
{!! Form::open(array('action' => 'RoundtablesController#postImage',$tables->id, 'files'=>true)) !!}
<div class="form-group">
{!! Form::label('Profile-Picture', 'Profile Picture:') !!}
{!! Form::file('profile_image',null,['class'=>'form-control']) !!}
</div>
<div class="form-group">
{!! Form::submit('Save', ['class' => 'btn btn-primary form-control']) !!}
</div>
{!! Form::close() !!}
</div>
This is my route
Route::post('/roundtables/settings',['uses'=>'RoundtablesController#postImage','middleware'=>['auth']]);
This is my controller ,the $name should get the Page Id, but look like the id not passed to here yet
public function postImage(Request $request,$name){
$table_details =Detail::find($name);
//save image
if ($request->hasFile('profile_image')) {
//add new photo
$image = $request->file('profile_image');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('images/' . $filename);
Image::make($image)->resize(800, 400)->save($location);
$oldFilename = $table_details->profile_image;
//update database
$table_details->profile_image = $filename;
//Delete old image
Storage::delete($oldFilename);
}
$table_details->update();
Can i know where is the error? Sry i know this is very basic but i am new in laravel.
Route:
Route::post('/roundtables/settings/{id}',
['as' => 'roundtables.setting',
'middleware'=>['auth'],
'uses'=>'RoundtablesController#postImage']);
Action:
public function postImage(Request $request, $id) {
$Detail = Detail::findOrFail($id); // will return 404 or exception if record not found
if ($request->hasFile('profile_image')) {
$file = $request->file('profile_image');
$profile_image = time() . '.' . $file->getClientOriginalExtension();
$profile_image_file = public_path('images/' . $profile_image);
Image::make($image)
->resize(800, 400)
->save($profile_image_file);
$old_profile_image_file = public_path('images/'.$Detail->profile_image);
if(is_file($profile_image_file)) { // if new file successfully created
$Detail->profile_image = $profile_image; // changing profile_image
$Detail->save(); // saving
Storage::delete($old_profile_image_file);
}
}
}
in view open form like (use named route: roundtables.setting defined in router):
{!! Form::open(array('url' => route('roundtables.setting', $tables->id), 'files'=>true)) !!}
also it's a little bit strange $tables->id, are You sure that $tables is an instance of model (not an array or collection) ?
route should be like
Route::post('/roundtables/settings/{name}',['uses'=>'RoundtablesController#postImage','middleware'=>['auth']]);
Try this way...
Route::get('groups/(:any)', array('as' => 'group', 'uses' => 'groups#show'));
class Groups_Controller extends Base_Controller {
public $restful = true;
public function get_show($groupID) {
return 'I am group id ' . $groupID;
}
}

Resources