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"
Related
I am using inertiajs and vue3 on my laravel project.
Problem:
When I try to login with an invalid credential toast message appears and disappears with animation as intended.
But after correct login toast message appear without animation, and doesn't disappear after a certain interval. Also same happens on logout
Toast Component
<template>
<transition
enter-active-class="transition-all ease-out duration-200"
enter-from-class="transform opacity-0 top-32 scale-95"
enter-to-class="transform opacity-100 top-22 scale-100"
leave-active-class="transition-all top-22 ease-in duration-200"
leave-from-class="transform opacity-100 scale-100"
leave-to-class="transform top-12 opacity-0 scale-95">
<div v-if="toast && show == true" class="absolute flex flex-col max-w-lg top-20 right-2 shadow-lg rounded pl-4 pr-2 pt-0 pb-2
bg-white/95 dark:bg-gray-800/95"
:class="{
'bg-green-600 dark:bg-green-600 shadow-green-600/40': toast.type == 'success',
'bg-red-600 dark:bg-red-600 shadow-red-600/40': toast.type == 'error'
}">
<div class="flex mb-2">
<div class="font-semibold"
:class="{
'text-white dark:text-white': toast.type == 'success',
'text-red-200 dark:text-red-200 hover:text-red-50 dark:hover:text-red-50': toast.type == 'error'
}">
{{toast.header}}
</div>
<button #click.prevent="show = false" class="focus:outline-none ml-auto"
:class="{
'text-green-200 dark:text-green-200 hover:text-green-50 dark:hover:text-green-50': toast.type == 'success',
'text-red-200 dark:text-red-200 hover:text-red-50 dark:hover:text-red-50': toast.type == 'error'
}" >
<XCircleIcon class="w-6 h-6" />
</button>
</div>
<div class="flex mr-6 items-center">
<div class="mr-2">
<CheckCircleIcon v-if="toast.type == 'success'" class="w-6 h-6"
:class="{
'text-green-50 dark:text-green-50': toast.type == 'success',
}" />
<XCircleNoFillIcon v-if="toast.type == 'error'" class="w-6 h-6"
:class="{
'text-red-50 dark:text-red-50': toast.type == 'error'
}" />
</div>
<div class="flex-1"
:class="{
'text-green-50 dark:text-green-50': toast.type == 'success',
'text-red-50 dark:text-red-50': toast.type == 'error'
}">
{{toast.message}}
</div>
</div>
</div>
</transition>
</template>
<script>
import { defineComponent, computed, reactive, watch, ref } from 'vue'
import { usePage } from '#inertiajs/inertia-vue3'
import CheckCircleIcon from '#/Icons/CheckCircle.vue'
import XCircleIcon from '#/Icons/XCircle.vue'
import XCircleNoFillIcon from '#/Icons/XCircleNoFill.vue'
export default defineComponent({
components: {
CheckCircleIcon, XCircleIcon, XCircleNoFillIcon,
},
setup() {
const toast = ref(computed(() => usePage().props.value.toast))
const show = ref(true)
watch(toast, () => {
setTimeout(() => {
show.value = true
}, 10);
hideToast()
})
function hideToast() {
setTimeout(() => {
console.log( toast.value.duration)
show.value = false
}, toast.value.duration);
}
return { toast, show }
},
})
</script>
AuthController
// Sign in
public function store(Request $request)
{
$credentials = Validator::make($request->all(), [
'email' => ['required', 'string', 'email', 'max:255'],
'password' => ['required', Rules\Password::defaults()],
]);
if($credentials->fails()) {
return back()
->withInput()
->withErrors($credentials)
->with([
'toast' => [
'duration' => '6000',
'type' => 'error',
'header' => 'Validation Error.',
'message' => 'Please resolve the issues.',
]
]);
}
if (!Auth::attempt($credentials->validated(), $request->remember ? true : false)) {
return back()
->withInput()
->withErrors(['email' => 'Invalid credentials'])
->with([
'toast' => [
'duration' => '1000',
'type' => 'error',
'header' => 'Failed!',
'message' => 'Invalid credentials.',
]
]);
}
$request->session()->regenerate();
return redirect()
->intended(RouteServiceProvider::HOME)
->with([
'toast' => [
'duration' => '5000',
'type' => 'success',
'header' => 'Signed in.',
'message' => 'Welcome back, ' . Auth::user()->name,
]
]);
}
Hello I am trying to post data via ajax but i face this error and i am sure that i called CSRF_TOKEN in header section
Header Section :
meta name="csrf-token" content="{{ csrf_token() }}"
Route Section :
Route::post('cart/data/store/{id}', [CartController::class, 'AddToCart']);
Ajax Code :
function addToCart() {
var product_name = $('#pname').text();
var id = $('#product_id').val();
var color = $('#color option:selected').text();
var size = $('#size option:selected').text();
var quantity = $('#qty').val();
$.ajax({
type:"POST",
dataType:"JSON",
data:{
color:color,
size:size,
quantity:quantity,
product_name:product_name,
},
url: "cart/data/store/"+id,
success:function(data) {
$('#closeModal').click();
console.log(data)
}
})
}
Controller :
class CartController extends Controller
{
public function AddToCart(Request $request, $id) {
$product = Product::findOrFail($id);
if ($product->discount_price == NULL) {
Cart::add([
'id' => $id,
'name' => $request->product_name,
'qty' => $request->quantity,
'price' => $product->selling_price,
'weight' => 1,
'options' => [
'image' => $product->product_thumbnail,
'size' => $request->size,
'color' => $request->color,
],
]);
return response()->json(['success' => 'Item Added To Your Cart']);
} else {
Cart::add([
'id' => $id,
'name' => $request->product_name,
'qty' => $request->quantity,
'price' => $product->discount_price,
'weight' => 1,
'options' => [
'size' => $request->size,
'color' => $request->color,
'image' => $product->product_thumbnail
],
]);
return response()->json(['success' => 'Item Added To Your Cart']);
}
}
}
Token Section :
$.ajaxSetup({
headers:{
'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')
}
add #csrf in beginning of your form.
<form id="my_form" >
#csrf
<input type="text" name="name"id="name" >
<button type="submit">submit</button>
</form>
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'],
]);
}
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 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());
}