How to upload an array of images with Laravel properly - php

I have a form like this:
<form action="{{ route('popups.store') }}" method="POST" enctype="multipart/form-data">
#csrf
<div id="dynamic_field">
<label>Date of showing</label>
<input type="text" id="date" name="datep" class="form-control datepicker" value="" autofocus>
<label for="title" class="control-label">Title</label>
<input type="text" id="title" name="title" class="form-control" value="" autofocus>
<label for="link" class="control-label">Link</label>
<input type="text" id="link" name="linkp[]" class="form-control" value="" autofocus>
<label for="bio" class="control-label">Text</label>
<textarea class="form-control" name="bio[]" rows="3"></textarea>
<label for="filep" class="control-label">Image</label>
<input type="file" class="form-control-file" id="filep" name="filep[]">
<button class="btn btn-success" type="submit">Submit</button>
<a id="add" class="btn btn-info" style="color:white">Add new form</a>
</div>
</form>
As you can see, I have added a link with id="add" for adding additional form fields dynamically with javascript.
So it means a user can add several images, texts and links. And that's why I used filep[], bio[] and linkp[], as the name of those form fields (in order to save them as an array).
Then at the Controller, I added this:
public function store(Request $request)
{
try{
$data = $request->validate([
'datep' => 'nullable',
'title' => 'nullable',
'linkp' => 'nullable',
'bio' => 'nullable',
'filep' => 'nullable',
]);
$newPop = Popup::create([
'datep' => $data['datep'],
'title' => $data['title']
]);
$files = $request->file('filep');
if($request->hasFile('filep'))
{
foreach ($files as $file) {
$newImageName = time() . '-' . $request->name . '.' . $request->filep->extension();
$request->filep->move(public_path('popups'), $newImageName);
Popup::where('id',$newPop->id)->update(['image_path'=>",".$newImageName]);
}
}
}catch (\Exception $e) {
dd($e);
}
return redirect()->back();
}
So for each image, I tried moving it into public/popups folder and then it should update the existing record of table with id of $newPop->id.
But it shows me this error:
Call to a member function extension() on array
Which is referring to this line:
$newImageName = time() . '-' . $request->name . '.' . $request->filep->extension();
So what's going wrong here? How can I upload multiple images with using array?

You can try this -
if($files=$request->file('filep')){
foreach ($files as $key=>$file) {
$extension = $file->getClientOriginalName();
$fileName = time().'-' .$request->name.'.'.$extension; // I don't know where did you get this $request->name, I didn't find it on your code.
$created = Popup::create([
'datep' => $request->datep[$key],
'title' => $request->title[$key],
'image_path' => $fileName
]);
if($created){
// $file->move('popups',$fileName); to store in public folder
// If you want to keep files in storage folder, you can use following : -
Storage::disk('public')->put('popups/'.$location,File::get($file));
// Dont't forget to run 'php artisan storage:link'
// It will store into your storage folder and you can access it by Storage::url('file_path)
}else{
// Your error message.
}
}
}

Related

Laravel errors while storing a file

I am working on a laravel crud project. Now i want to store files like .xlsx and .docx
But i keep getting errors in my controller and browser:
Controller:
public function store(Request $request)
{
$request->validate([
'title'=>'required',
'description_short'=>'',
'description_long'=>'',
'file'=>'',
'language_id'=> [
'required', 'exists:language,id'
],
]);
$fileName = $request->file->getClientOriginalName();
$filePath = 'files/' . $fileName;
$path = Storage::disk('public')->put($filePath, file_get_contents($request->file));
$path = Storage::disk('public')->url($path);
$file = new File([
'title'=> $request->get('title'),
'description_short'=> $request->get('description_short'),
'description_long'=> $request->get('description_long'),
'file'=>$request->get('file'),
'language_id'=> $request->language_id,
]);
$file->save();
return back();
}
Here i get the error: Undefined method 'url'
Create page:
<form method="post" action="{{ route('admin.language.store') }}" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label for="title">{{('name')}}</label>
<input type="text" class="form-control" name="name"/>
</div>
<div class="form-group">
<label for="value">{{('file')}}</label>
<input type="file" class="form-control" name="file"/>
</div>
<button type="submit" class="btn btn-primary">Add language</button>
</form>
the browser error i get is : Call to a member function getClientOriginalName() on string.
if i need to provide more information i will gladly do so!
file is reserved keyword in Request class to get submitted Files in post method.
You can not use file in input. So first you have to change file name in input box.
After that you can do like below.
$request->file('file_input_name')->getClientOriginalName();
$file = $request->file->getClientOriginalName();
fixed it

Laravel 8, how to upload more than one image at a time

I want to upload more than one image at a time through an in Laravel 8 to my SQL database, and I am not able to do it. I have managed to upload only one, but when I try with more I get failure.
My Database
Imagenes
id
nombre
id_coche
01
name.jpg
0004
...
...
...
My Code
Blade with the Form
#foreach ($Vehiculo as $obj) /*this is to take the Car ID*/
<form method="POST" action="{{ route('añadirImagen')}}" enctype="multipart/form-data" >
#csrf
<div class="form-row">
<div class="form-group col-md-3">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">ID</span>
</div>
<input type="text" class="form-control" name="id_coche" value="{{$obj->id}}" style="background: white" required readonly>
</div>
</div>
<div class="col-md-6">
<input type="file" class="form-control" name="imagen" required multiple/>
</div>
<div class="form-group col-md-3">
<button type="submit" class="btn btn-success">AÑADIR IMAGENES</button>
</div>
</div>
</form>
#endforeach
Controller
"To upload only one image"
public function añadirImagen(Request $request){
$validated = $request->validate([
'id_coche' => 'required',
'nombre.*' => 'mimes:image'
]);
$data = $request->input();
$id_coche = $data['id_coche'];
$Imagenes= new Imagenes;
$Imagenes->id_coche = $id_coche;
if($request->file("imagen")!=null){
$nombre = $request->file('imagen');
$nombreFoto = $nombre->getClientOriginalName();
$nombre->move('img/Coches/', $nombreFoto);
$Imagenes->nombre = $nombreFoto;
}
$Imagenes->save();
return redirect()->back()->with('error','Se han añadido las imagenes correctamente.');
}
}
"My attempt to upload more than one"
public function añadirImagen(Request $request){
$validated = $request->validate([
'id_coche' => 'required',
'imagen.*' => 'mimes:image'
]);
$data = $request->input();
$id_coche = $data['id_coche'];
$Imagenes= new Imagenes;
$Imagenes->id_coche = $id_coche;
if($request->hasfile("imagen")){
$nombre_img = $request->file('imagen');
foreach($nombre_img as $nombre) {
$nombreFoto = $nombre->getClientOriginalName();
$nombre->move('img/Coches/', $nombreFoto);
$Imagenes->nombre = $nombreFoto;
}
}
$Imagenes->save();
When doing this, it adds in the database a single row, with the correct id_coche, the Auto_Increment does well the ID, but the name remains NULL.
Thank You.
You currently have:
<input type="file" class="form-control" name="imagen" required multiple/>
and it needs to be:
<input type="file" class="form-control" name="imagen[]" required/>
multiple attribute is not required.
Then you can do in your controller:
if($request->hasfile('imagen')) {
foreach($request->file('imagen') as $file)
{
...
}
}

Not update categories table in Laravel 5.6?

working with Laravel 5.6 and MySQL. I am going to update categoryname and image in my categories table using the following controller function?
public function update(Request $request, $id)
{
if ($request->isMethod('get'))
return view('categories.form', ['image' => Category::find($id)]);
else {
$rules = [
'categoryname' => 'required',
];
$this->validate($request, $rules);
$image = Category::find($id);
if ($request->hasFile('image')) {
$dir = 'images/';
if ($image->image != '' && File::exists($dir . $image->image))
File::delete($dir . $image->image);
$extension = strtolower($request->file('image')->getClientOriginalExtension());
$fileName = str_random() . '.' . $extension;
$request->file('image')->move($dir, $fileName);
$image->categoryimage = $fileName;
} elseif ($request->remove == 1 && File::exists('images/' . $image->image)) {
File::delete('images/' . $image->post_image);
$image->categoryimage = null;
}
}
$image->categoryname = $request->categoryname;
$image->save();
return redirect()->route('categories.index');
}
and route
Route::match(['get', 'put'], 'category/update/{id}', 'CategoryController#update');
and edit form
#if(isset($image))
<form method="PUT" action="http://localhost:8000/category/update/{{$image->id}}" enctype="multipart/form-data">
<input type="hidden" name="_method" value="put">
<label for="description" class="col-form-label col-md-3 col-lg-2">Description</label>
<div class="col-md-8">
<input class="form-control" autofocus placeholder="Description" name="categoryname" type="text" id="categoryname" value="{{ isset($image) ? $image->categoryname : '' }}">
<label for="image" class="col-form-label col-md-3">Image</label>
<div class="col-md-5">
<img id="preview"
src="{{asset((isset($image) && $image->categoryimage!='')?'images/'.$image->categoryimage:'images/noimage.png')}}"
height="200px" width="200px"/>
<input class="form-control" style="display:none" name="image" type="file" id="image" name="_token" value="{{ csrf_token() }}">
<br/>
Add Image |
<a style="color: red" href="javascript:removeImage()">Remove</a>
<input type="hidden" style="display: none" value="0" name="remove" id="remove">
but when I try to update data it is not updating. only refresh to the same page. no, any error
url look like this
http://localhost:8000/category/update/21?categoryname=tractorrer&image=&remove=0 //tractorrer is updated category name
how can fix this problem?
Theres a few things concerning about your code examples. Like only having 1 method called update for both GET and PUT routes. Probably not a good habit to get into. Especially since, if it is a get route, you're not updating anything. So already the method name / description of what it does, is wrong.
But that aside, you are not seeing anything because you cannot use method="PUT" on your form. You need to use method="POST" and then inside your form, you need these lines. One to tell the form that this is a patch request, and one to put the csrf token in.
{{csrf_field()}}
{{ method_field('PATCH') }}
and I would update your route to PATCH, not PUT.
First.
Have you dump all of the request like this to check whether it contains categoryname.
dd($request->all());
If the dd does not print categoryname value, then it seems to be the problem when you sending request.
Then.
Try using method="POST" instead of method="PUT" If you have not try yet.
I have never used PUT with form submit before
First,
You set POST instead of PUT of form method.
Second,
Your codes look a little messy. I updated your action codes;
public function update(Request $request, $id)
{
if ($request->isMethod('get')){
return view('categories.form', ['image' => Category::find($id)]);
} else{
$rules = [
'categoryname' => 'required',
];
$this->validate($request, $rules);
$image = Category::find($id);
if ($request->hasFile('image')) {
$dir = 'images/';
if ($image->image != '' && File::exists($dir . $image->image))
File::delete($dir . $image->image);
$extension = strtolower($request->file('image')->getClientOriginalExtension());
$fileName = str_random() . '.' . $extension;
$request->file('image')->move($dir, $fileName);
$image->categoryimage = $fileName;
} elseif ($request->remove == 1 && File::exists('images/' . $image->image))
{
File::delete('images/' . $image->post_image);
$image->categoryimage = null;
}
$image->categoryname = $request->categoryname;
$image->save();
return redirect()->route('categories.index');
}
}
Can you try again with my directives. I hope it helping your problem.

How to Solve Error: Call to a member function move() on string

I am uploading an image to a folder and saving data to the database. How can I solve this error? The error is in the following line...
$property_features_image->move($destinationPath,$property_features_image);
public function store(Request $request)
{
$this->validate($request, [
'property_feature' => 'required|unique:property_features,property_features_name',
'property_icon' => 'required|image|mimes:jpg,png,jpeg|max:10240',
]);
$property_features_name = $request->property_feature;
$property_features_image = $request->file('property_icon');
$property_features_image = $property_features_image->getClientOriginalExtension();
$destinationPath = public_path('/images');
$property_features_image->move($destinationPath, $property_features_image);
DB::table('property_features')->insert([
'property_features_name' => $property_features_name,
'property_features_image' => $property_features_image,
]);
}
Blade
<form method="post" enctype="multipart/form-data" action="{{url('/admin/property-features')}}">
<div class="form-group">
<input type="hidden" value="{{csrf_token()}}" name="_token"/>
<label for="Property">Add Property Feature</label>
<input type="text" class="form-control" id="property_feature" name="property_feature"
placeholder="Enter Property Feature">
<label for="exampleFormControlFile1">Property Features's Icon</label>
<input type="file" class="form-control-file" id="property_icon" name="property_icon">
<?php echo($errors->first('property_feature', "<li class='ab' style='color:red;'>:message</li>"));?>
<?php echo($errors->first('property_icon', "<li class='ab' style='color:red;'>:message</li>"));?>
</div>
</form>
This line:
$property_features_image = $property_features_image->getClientOriginalExtension();
Assigns $property_features_image variable to a string value.
And strings cannot have any methods (you are trying to call move() method).
So removing the line should help, but then you must ensure everything else is ok. The getClientOriginalExtension() might be required somewhere, but we don't see all the code.

FileNotFoundException in laravel

In laravel i am making an application that uploads a file and the user can download that same file.
But each time i click to upload i get this error.
FileNotFoundException in File.php line 37: The file
"H:\wamp64\tmp\phpF040.tmp" does not exist
my view code is this:
#extends('layouts.app')
#section('content')
#inject('Kala','App\Kala')
<div class="container">
<div class="row">
#include('common.errors')
<form action="/addkala" method="post" enctype="multipart/form-data">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="text" name="name">
<input type="text" name="details">
<input type="file" name="photo" id="photo" >
<button type="submit">submit</button>
</form>
</div>
</div>
#endsection
and my controller
public function addkalapost(Request $request)
{
$rules = [
'name' => 'required|max:255',
'details' => 'required',
'photo' => 'max:1024',
];
$v = Validator::make($request->all(), $rules);
if($v->fails()){
return redirect()->back()->withErrors($v->errors())->withInput($request->except('photo'));
} else {
$file = $request->file('photo');
$fileName = time().'_'.$request->name;
$destinationPath = public_path().'/uploads';
$file->move($destinationPath, $fileName);
$kala=new Kala;
$kala->name=$request->name;
return 1;
$kala->details=$request->details;
$kala->pic_name=$fileName;
$kala->save();
return redirect()->back()->with('message', 'The post successfully inserted.');
}
}
and i change the upload max size in php.ini to 1000M.
plz help
im confusing
I'll recommend you using filesystems for that by default the folder is storage/app you need to get file from there
if your file is located somewhere else you can make your own disk in config/filesystems e.g. 'myDisk' => [
'driver' => 'local',
'root' =>base_path('xyzFolder'),
],
and you can call it like
use Illuminate\Support\Facades\Storage;
$data = Storage::disk('myDisk')->get('myFile.txt');
this is obviously to get file and you can perform any other function by following laravel docs.

Categories