I am trying to Upload multiple images into a database but only one is uploading instead of multiple.
How to upload multiple images into a database?
Could anyone tell me what is wrong with my code?
[database table ][1]
[1]: https://i.stack.imgur.com/kgv4r.png
controller
public function singalprojectaction(Request $request)
{
$input=$request->all();
$images=array();
if($files=$request->file('images')){
foreach($files as $file){
$name=$file->getClientOriginalName();
$file->move(public_path('projects'), $name);
$images[]=$name;
}
}
$query=DB::table('single_portfolio')->insert( [
'Project_name' =>$input['project_name'],
'Client_Name' =>$input['Client_name'],
'Completion_date' =>$input['Completion_date'],
'Duration' =>$input['Duration'],
'project_image_one'=> implode("|",$images),
'Description' =>$input['Description'],
'project_id' =>$input['select_project'],
]);
if($query)
{
return response()->json([
'message' => 'Image is Successfully Inserted',
'class_name' => 'alert-success'
]);
}
else{
return response()->json([
'message' => 'Data is not inserted Inserted',
'class_name' => 'alert-warning'
]);
}
}
html view
<form action="Route('singal.action') }}" id="singal_project"
enctype="multipart/form-data">
{{ csrf_field() }}
<div class="alert" id="message" style="display:block;"></div>
<div class="group-form">
<label>Drop Multple Imges</label>
<input required type="file" class="form-control" name="images[]"
multiple>
</div>
</form>
Try This To insert multiple images
public function singalprojectaction(Request $request)
{
$input=$request->all();
$datas = [];
$result = [];
if ($request->hasfile('images')) {
foreach ($request->file('images') as $key => $file) {
$name = $file->getClientOriginalName();
$file->move(public_path() . '/projects/', $name);
$datas[$key] = $name;
}
}
$query=DB::table('single_portfolio')->insert( [
'Project_name' =>$input['project_name'],
'Client_Name' =>$input['Client_name'],
'Completion_date' =>$input['Completion_date'],
'Duration' =>$input['Duration'],
'project_image_one'=> implode("|",$datas);
'Description' =>$input['Description'],
'project_id' =>$input['select_project'],
]);
if($query){
return response()->json(['message' => 'Image is Successfully Inserted','class_name' => 'alert-success']);
}
else{
return response()->json(['message' => 'Data is not inserted Inserted','class_name' => 'alert-warning'
]);
}
}
You will have to wrapped the insert code in the foreach statement: see below
foreach($files as $file){
$name=$file->getClientOriginalName();
$file->move(public_path('projects'), $name);
$query=DB::table('single_portfolio')->insert( [
'Project_name' =>$input['project_name'],
'Client_Name' =>$input['Client_name'],
'Completion_date' =>$input['Completion_date'],
'Duration' =>$input['Duration'],
'project_image_one'=> $name),
'Description' =>$input['Description'],
'project_id' =>$input['select_project'],
]);
}
Related
i'm trying to upload image and video at the same time but couldn't
i've tried this but it seems to not work, the image file will upload successfully but the video won't
$request->validate([
'title'=> 'required',
'description' => 'required',
'file' => 'required|mimes:jpg,jpeg,png|max:2048',
'video' => 'required|mimes:mp4'
]);
$film= Film::create([
'title' => $request->title,
'slug' => Str::slug($request->title),
'description' => $request->description,
'user_id' => auth()->id()
]);
$file = new Film();
if($request->file('file')) {
$file_name = time().'_'.$request->file->getClientOriginalName();
$file_path = $request->file('file')->storeAs('uploads', $file_name, 'public');
$file->name = time().'_'.$request->file->getClientOriginalName();
$file->file = '/storage/' . $file_path;
$film->update(['file' => $file_name]);
$film->update(['path' => $file_path]);
return response()->json(['success'=>'File uploaded successfully.']);
}
if ($request->file('video')){
$file_name = time().'_'.$request->file->getClientOriginalName();
$file_path = $request->file('video')->storeAs('uploads', $file_name, 'public');
$file->name = time().'_'.$request->file->getClientOriginalName();
$file->file = '/storage/' . $file_path;
$film->update(['video' => $file_name]);
$film->update(['videoPath' => $file_path]);
return response()->json(['success'=>'File uploaded successfully.']);
}
It's because you are returning a response after you process the image file so the condition for the video can't be reached. If you want to process both just return after all the operations are done.
$request->validate([
'title'=> 'required',
'description' => 'required',
'file' => 'required|mimes:jpg,jpeg,png|max:2048',
'video' => 'required|mimes:mp4'
]);
$film= Film::create([
'title' => $request->title,
'slug' => Str::slug($request->title),
'description' => $request->description,
'user_id' => auth()->id()
]);
if($request->file('file')) {
$file_name = time().'_'.$request->file->getClientOriginalName();
$file_path = $request->file('file')->storeAs('uploads', $file_name, 'public');
$film->update([
'file' => $file_name,
'path' => $file_path
]);
}
if ($request->file('video')){
$file_name = time().'_'.$request->video->getClientOriginalName();
$file_path = $request->file('video')->storeAs('uploads', $file_name, 'public');
$film->update([
'video' => $file_name,
'videoPath' => $file_path
]);
}
return response()->json(['success'=>'Files uploaded successfully.']);
You can also add additional checks if the files inside each condition is processed successfully.
The $file variable is unnecessary and it's not even saved so that can be removed as well.
As for the reason it's uploading twice, you are calling ->file again inside the video condition which should be ->video.
And as an aside, you can update multiple fields at once by passing multiple array items instead of calling update for each property which can save you db requests.
jech chua, thanks it worked but it uploads the image twice.
maybe there a problem in my blade
<form action="/film" class="form" method="POST" enctype="multipart/form-data">
#csrf
<div class="f">
<div class="sect1">
<input type="text" class="input" name="title" placeholder="Title..">
<textarea name="description" class="textarea" placeholder="Description.."></textarea>
<h2>Upload image</h2><input type="file" name="file" class="file">
</div>
<div class="dropz" id="image-upload">
<h2>Upload video</h2>
<input type="file" name="video">
</div>
</div>
<button type="submit" class="buttn">Create film</button>
</form>
I'm trying to upload an image with another field to like the patreon image post.
I use Laravel as a backend and have been tested WORK using postman.
But for the frontend part using the q-uploader Quasar Framework - vue js, it seems I need some advice.
this is my laravel controller:
public function createImagePost(Request $request) {
$validator = Validator::make($request->all(),[
'title' => 'required',
'permission' => 'required',
'images' => 'required',
]);
if ($validator->fails()) {
return response()->json([
'status' => 'failed',
'errors' => $validator->errors()
], 500);
} else {
if ($request->hasfile('images'))
{
$images = $request->file('images');
$names = array();
foreach($images as $image) {
$imageName = Auth::user()->id.'_image_'.time().'.'.$image->getClientOriginalExtension();
$image->storeAs('user_post_images', $imageName);
$names[] = $imageName;
}
UserPost::create([
'images' => json_encode($names),
'title' => $request->title,
'tags' => $request->tags,
'description' => $request->description,
'permission' => $request->permission,
'post_user_id' => Auth::user()->id
]);
return response()->json([
'status' => 'success',
'message' => 'Post has been created successfully!'
], 200);
} else {
return response()->json([
'status' => 'ERROR VRO',
'message' => 'ERROR'
], 500);
}
}
}
and this is the quasar frontend:
<q-form #submit="createImagePost">
<q-card-section class="q-pt-none">
<!-- Fields -->
<q-uploader
label="Pick Some Images Here!"
multiple
color="teal"
accept="image/*"
style="max-width: 1200px; width: 100%"
flat
bordered
:factory="createImagePost"
url=""
ref="imageUploader"
/>
<br>
<q-input
type="text"
hint="Required"
label="Post Title"
v-model.trim="post_title"
#input="$v.post_title.$touch()"
:rules="[
val => $v.post_title.required || 'Post Title is required',
]"
:dense="dense"
/>
<br>
<q-input
type="textarea"
v-model="post_description"
hint="Tell a story"
label="Post Description"
:dense="dense"
/>
<br>
<div class="row">
<div class="col q-mr-md">
<q-select
outlined
:options="post_permission_options"
label="Permission"
hint="Required"
v-model.trim="post_permission"
#input="$v.post_permission.$touch()"
:rules="[
val => $v.post_permission.required || 'Post permission is required',
]"
/>
</div>
<div class="col">
<q-select
label="Tags"
outlined
v-model="post_tags"
use-input
use-chips
multiple
hide-dropdown-icon
input-debounce="0"
new-value-mode="add"
/>
</div>
</div>
</q-card-section>
<q-card-actions align="right" class="text-primary">
<q-btn flat label="Cancel" v-close-popup />
<q-btn flat label="Create" type="submit"/>
</q-card-actions>
</q-form>
createImagePost(files) {
let currentObj = this
currentObj.createImagePostLoading = true
const config = {
headers: { 'Content-Type': undefined }
}
const fd = new FormData()
fd.append('images', files)
fd.append('title', currentObj.title)
fd.append('tags', currentObj.tags)
fd.append('description', currentObj.description)
fd.append('permission', currentObj.permission)
axios.get('/sanctum/csrf-cookie').then(response => {
axios.post('/api/create-image-post', fd, config)
.then(function (response) {
currentObj.serverSuccess = response.data.message
currentObj.showCreatePostSuccess()
currentObj.createImagePostLoading = false
currentObj.create_image_post = false
currentObj.selected_file = []
})
.catch(function (error) {
if(error.response.data) {
currentObj.serverError = error.response.data.errors
}
currentObj.showCreatePostError()
currentObj.createImagePostLoading = false
currentObj.create_image_post = false
currentObj.errorModal = true
currentObj.selected_file = []
})
})
},
and the error message is the same as the error message that is made if the file is not found. but for this controller it works if I use postman, am I missing something with q-uploader?
Error Message :
{status: "ERROR VRO", message: "ERROR"}
status: "ERROR VRO"
message: "ERROR"
I’m working on a CRUD system for inventory management, in which images for each product should be included. Every time that I try to save the path of the image in the DB this error appears:
Undefined variable: image
My controller looks like this:
public function store(Request $request)
{
if (Auth::user('logistics')) {
$product = $this->validate(request(), [
'Product_Name' => 'required',
'Amount' => 'required|numeric',
'MinAmount' => 'required|numeric',
'Status' => 'required',
'Supplier' => 'required',
'WebLink' => 'required',
]);
if ($request->hasFile('Product_Image')) {
$image = Storage::putFile('public/pictures/LogInv/', $request->Product_Image);
}
$product['Product_Image'] = $image;
$product['Employee_id'] = Auth::user()->id;
LogisticsInv::create($product);
return back()->with('success', 'Product has been added');
} else {
return view('/restricted_area');
}
}
and my input looks like this:
<form method="post" action="{{url('loginv')}}" enctype="multipart/form-data">
{{csrf_field()}}
<div class="row">
<div class="col-md-12"></div>
<div class="form-group col-md-12">
<label for="Product_Image">Product Image:</label>
<input type="file" class="form-control" name="Product_Image">
</div>
</div>
and dd($request->all()); delivers this
array:8 [▼ "_token" => "P7m8GP4A35G1ETUosduBSWtMpJuPaNILn2WI6Al3"
"Product_Image" => "6.jpg" "Product_Name" => "asd" "Amount" =>
"123" "MinAmount" => "1" "Status" => "Ok" "Supplier" => "asd"
"WebLink" => "asd" ]
Change your code to
public function store(Request $request)
{
if (Auth::user('logistics')) {
$product = $this->validate(request(), [
'Product_Name' => 'required',
'Amount' => 'required|numeric',
'MinAmount' => 'required|numeric',
'Status' => 'required',
'Supplier' => 'required',
'WebLink' => 'required'
]);
if ($request->hasFile('Product_Image')) {
$image = Storage::putFile('public/pictures/LogInv/', $request->Product_Image);
$product['Product_Image'] = $image;
}
$product['Employee_id'] = Auth::user()->id;
LogisticsInv::create($product);
return back()->with('success', 'Product has been added');
} else {
return view('/restricted_area');
}
}
I have this in the controller...
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'category_id' => 'required',
'description' => 'required',
'price' => 'required',
'long_description' => 'required'
]);
$product = new Product();
foreach ($request->all() as $key => $value) {
if ($key !== '_token') $product->$key = $value;
}
$product->save();
return redirect('/admin/products');
}
And this in the view...
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
The form without the validation works perfect. But I do not understand why he does not show me the errors in the view when redirected.
You need to do something like this-
public function store(Request $request)
{
$request->validate($request, [
'name' => 'required',
'category_id' => 'required',
'description' => 'required',
'price' => 'required',
'long_description' => 'required'
]);
if (!$validator->fails()) {
$product = new Product();
foreach ($request->all() as $key => $value) {
if ($key !== '_token') $product->$key = $value;
}
$product->save();
return redirect('/admin/products');
} else {
\Session::flash('errors', $validator->messages());
return redirect()->back()->withInput();
}
}
I made two changes in your code-
Added validate method on $request instead of $this.
Added a check for failed validation and sent those errors through a session.
I have already solved. The problem was that I had the post route inside api.php. By moving it to web.php it works.
i create image module and i edit image more then 1mb then can not show errormsg.
i used codigniter fremwork.
controller:
public function edit($id) {
$this->edit_status_check($id);
$this->form_validation->set_rules('agent_name', 'Agent Name', 'required');
$this->form_validation->set_rules('mobile', 'Mobile No.', 'required');
$this->form_validation->set_rules('agent_vehicle', 'Agent Vehicle', 'required');
if ($this->form_validation->run() == FALSE) {
$data = array(
'page_title' => 'Edit Agent',
'page_name' => 'agent/edit',
'result' => $this->agent_model->select_id($id),
'result_vehicle' => $this->vehicle_model->list_all(),
'error' => validation_errors(),
'id' => $id
);
$this->load->view('template', $data);
} else {
$config['upload_path'] = '../uploads/agent/';
$config['allowed_types'] = 'jpg|jpeg';
$config['encrypt_name'] = TRUE;
$config['max_size'] = 1000; // 1 mb
$this->load->library('upload', $config);
if (!empty($_FILES['agent_image']['name'])) {
if ($this->upload->do_upload('agent_image')) {
$_POST['agent_img_url'] = 'uploads/agent/' . $this->upload->data('file_name');
} else {
$data = array(
'page_title' => 'Edit Agent',
'page_name' => 'agent/edit',
'result' => $this->agent_model->select_id($id),
'result_vehicle' => $this->vehicle_model->list_all(),
'error' => $this->upload->display_errors(),
'id' => $id
);
$this->load->view('template', $data);
}
}
$this->agent_model->update($_POST, $id);
alert('Update', $_POST['agent_name']);
redirect('agent');
}
}
Model:
public function update($data, $id) {
$updatedata = array(
'name' => $data['agent_name'],
'mobile' => $data['mobile'],
'password' => sha1($data['password']),
'vehicle' => $data['agent_vehicle'],
'address' => $data['agent_address'],
'category' => $data['category'],
'created_on' => date('Y-m-d h:i:sa')
);
if (!empty($data['agent_img_url'])) {
$updatedata['img_url'] = $data['agent_img_url'];
}
$this->db->where('id', $id);
$this->db->update('agent', $updatedata);
}
View:
<div class="form-group">
<img src="/<?= $result['img_url']; ?>" class="img-responsive" name="old_agent_image" width="133" height="100">
</div>
<div class="form-group">
<label>Agent Image</label>
<input type="file" name="agent_image">
</div>
MY question: I edit image for particular user then image uploaded,but if image size more then 1mb ,then image can not upload and display error message.
so my question how to show errormsg.
$uploaded = $this->upload->do_upload('file'); //'file' is input field name
if($uploaded) {
$upload_data = $this->upload->data();
// do database stuff
} else {
$data['errors'] = array("error" => $this->upload->display_errors());
}