Image file not properly stored in Mysql database with Laravel - php

Here i try to store the user's image in the db when they upload it in the form , When they upload it the image is getting stored in the databse but in the form of BIN file which size is just 7 Bytes or 14 bytes and in the db it looks like [BLOB-14B] and [BLOB-7B]. But when i checked by directly uploading it on the database it worked pretty fine. What is the cause of the issue here
Here is the code of the form to get users image
<div class="form-group">
<label class="col-md-4 control-label">Upload image</label>
<div class="col-md-6">
<input type="file" class="form-control" name="image" id="image">
</div>
</div>
I am not including the whole form code here and have included only the code that gets image file.
Here is the controller function code
public function prof_details(Request $request)
{
$post = $request->all();
$val=\Validator::make($request->all(),
[
'firstname' => 'required',
'lastname' => 'required',
'username' => 'required',
'phone'=> 'required',
'nationality' => 'required',
'dobmonth' => 'required',
'dobyear' => 'required',
'dobday' => 'required',
'image' => 'required',
]
);
if ($val ->fails())
{
return redirect()->back()->withErrors($val->errors());
}
else
{
$data = array(
'firstname' => $post['firstname'] ,
'lastname' => $post['lastname'],
'username' => $post['username'],
'phone' => $post['phone'],
'nationality' => $post['nationality'],
'dobmonth' => $post['dobmonth'],
'dobyear' => $post['dobyear'],
'dobday' => $post['dobday'],
'image' =>$post['image'],
);
$updatedata = DB::table('users')->where('name',\Auth::user()->name)
->update($data);
if ($updatedata>0) {
return redirect('home');
}
else
{
return "something";
}
}
}

<input type="file" class="form-control" name="image" id="image">
Files are not stored in the $_POST variable but instead are stored in a temp file. You can obtain data on this file from the $_FILES variable 1 [2].
So, your uploaded file information would be in $_POST['image']. In order to obtain the actual image you would need to read the temp file that is stored in $_POST['image']['tmp_name'].

Related

How to return file image name in database after upload in Laravel 9?

The image uploads fine, it moves to the required folder, but the path name is not being returned into my database, it stays null
Posts Controller
if($request->hasFile('image')) {
$fileName = $request->file('image');
$file_name = $fileName->getClientOriginalName();
$formFields['image'] = $request->file('image')->store('img','public');
}
Posts::create([
'title' => $request->post('title'),
'sub_title' => $request->post('sub_title'),
'tags' => $request->post('tags'),
'content' => $request->post('content'),
'featured' => ($request->has('featured')) ? true : false,
]);
Image upload input
<div class="mb-2">
<label for="image" class="mb-1">Image</label>
<input type="file" class="w-100" name="image">
#error('image')
<p class="mt-1 text-danger">{{ $message }}</p>
#enderror
</div>
You must add filename field in your table, the file moves to the required folder but after that you must assign the filename in a filed in Posts table like this :
Posts::create([
'title' => $request->post('title'),
'sub_title' => $request->post('sub_title'),
'tags' => $request->post('tags'),
'content' => $request->post('content'),
'featured' => ($request->has('featured')) ? true : false,
'filename' => $file_name // add this line
]);
Take a look at the code used at this timestamp. Notice that he is adding the image from the $request to his $formFields array which is an array of validated $request fields before passing the $formFields array to the create method on the object. You need to replicate that process.
$formFields = [
'title' => $request->post('title'),
'sub_title' => $request->post('sub_title'),
'tags' => $request->post('tags'),
'content' => $request->post('content'),
'featured' => ($request->has('featured')) ? true : false,
];
if ($request->hasFile('image')) {
$formFields['image'] = $request->file('image')->store('img','public');
}
Posts::create($formFields);
Side note, I have omitted $request input validation but you'll want to perform validation on the $request inputs. Never trust input.

"General error: 1366 Incorrect integer value" even though I have set validation to nullable

I get this error:
When I am trying to create and I am not filling the input for fixed_quantity
This is my store in my Controller(I have set fixed_quantity to nullable so it should be fine right?):
$this->validate($request, [
'name' => 'required',
'description' => 'required',
'fixed_quantity' => 'nullable',
'max_increments' => 'required|numeric|min:0',
]);
DB::transaction(function () use ($request, $store, $variant) {
$subscription_plan = new SubscriptionPlan([
'store_id' => $store->uuid,
'variant_id' => $variant->uuid,
'name' => $request->input('name'),
'description' => $request->input('description'),
'max_increments' => $request->input('max_increments'),
]);
$subscription_plan->fixed_quantity = $request->input('fixed_quantity');
$subscription_plan->save();
This is what is on my blade:
<div class="form-group">
<label for="fixed_quantity">Quantity</label>
<input class="form-control" type="number" id="fixed_quantity" name="fixed_quantity" value="{{ old('fixed_quantity') }}"" placeholder="0">
</div>
If you look closely, the error is saying that it's trying to put '' in the column.
Check if the input is empty and don't set it if it is.
if (!empty($request->input('fixed_quantity')))
$subscription_plan->fixed_quantity = $request->input('fixed_quantity');
try this
check fixed_quantity before insert
'fixed_quantity' => $request->has('fixed_quantity') ? $request->input('fixed_quantity') : NULL,
this nullable store as string on integer field thats why
'fixed_quantity' => 'nullable',
nullable means that null is an acceptable value, but you are passing it an empty string (''), which is not. Change your code to something like this:
$subscription_plan->fixed_quantity = !empty($request->input('fixed_quantity')) ? $request->input('fixed_quantity') : null;

Why is my image not storing in a specified folder in Laravel 5.6?

In my form, I asked for an image to upload. Then I already validated it and it works. But the file is not stored in the uploads folder.
Here's a snippet of my ProductController:
public function store(Request $request)
{
// Validate fields
$this->validate($request, [
'product_name' => 'required',
'product_price' => 'required',
'product_desc' => 'required',
'product_img' => 'image|required'
]);
// Upload image
if($request->hasFile('image')) {
app()->make('path.public/uploads');
$image = $request->image;
$image->move('uploads', $image->getClientOriginalName());
}
/*// Save the data into database
Product::create([
'name' => $request->product_name,
'price' => $request->product_price,
'description' => $request->product_desc,
'image' => $request->image->getClientOriginalName()
]);
// Echo a session message
$request->session()->flash('msg', 'Your product has been added');
// Redirect to view page
return redirect('/products');*/
}
I already tried looking at other possible solutions but the other questions were already at storing the image in the database. I also tried checking if uploads was a directory and existed, and it is.
Can anyone please help? Thanks.
Try this: official documentation: This is how it should look in your controller:
if($request->hasFile('image')) {
$request->file('image')->store('uplodads/', 'public');
}
This would store the image in /storage/app/public/uploads by default. You can also change the public path in /config/filesystems.php. You can then access the file (if you linked the storage) with asset('storage/uploads'.$img_name).
app()->make('path.public/uploads');
I've already solved it. The variable was wrong all along. Instead of it being product_img, I placed image.
Here's the updated code:
// Validate fields
$this->validate($request, [
'product_name' => 'required',
'product_price' => 'required',
'product_desc' => 'required',
'product_img' => 'image|required'
]);
// Upload image
if($request->hasFile('product_img')) {
$image = $request->product_img;
$image->move('uploads', $image->getClientOriginalName());
}

Laravel image uploader

I'm trying to do a image upload on a form method but when i'm validating it always return an error saying the file is not an image. here you can see my html image uploader form:
<div class="row form-group">
<h4><strong>Imagen</strong></h4>
<input type="file" id="picture" name="picture" accept=".jpeg,.jpg,.png">
</div>
and my controller where i'm making my validation:
$this->validate(request(),[
'nombre' => 'required|min:5',
'precio' => 'required|numeric',
'descripcion' => 'required|min:10',
'alto' => 'required|numeric',
'ancho' => 'required|numeric',
'largo' => 'required|numeric',
'categoria' => 'required|numeric',
'picture' => 'image|required',
]);
$store = new articulo();
$store->nombre = request('nombre');
$store->categoria_id = request('categoria');
$store->precio = request('precio');
$store->descripcion = request('descripcion');
$store->alto = request('alto');
$store->ancho = request('ancho');
$store->largo = request('largo');
$store->image = request('picture');
$store->save();
For image validation try this:
'picture' => 'mimes:jpeg,jpg,png|required'
You can also add max:5000 file size validation.
Hope that help
To upload an image your form must have the attribute enctype="multipart/form-data" so it submits the image as a file and not a string. Your form should be similar to this:
<form action="/yourroute" method="post" enctype="multipart/form-data">
....
<div class="row form-group">
<h4><strong>Imagen</strong></h4>
<input type="file" id="picture" name="picture" accept=".jpeg,.jpg,.png">
</div>
....
</form>

Validation doesn't work for image upload in laravel 5

I have problem when validating inputs. All input fields pass the validation process except image fields.
This is my file upload code in html:
<div class="control-group">
<label class="control-label" for="fileInput"> Cover picture: </label>
<div class="controls">
{!! Form::file('cover') !!}
</div>
</div>
And how I get data from view in controller:
$datas = array(
'name' => Input::get('name'),
'color' => Input::get('color'),
'size' => Input::get('size'),
'cover' => array('cover' => Input::file('cover'))
);
And this is rules:
$rules = array(
'name' => 'required',
'color' => 'required',
'size' => 'required',
'cover' => 'required|mimes:jpeg,jpg,png|max:10000'
);
And Validation facades`s make method:
$validator = Validator::make($datas, $rules);
As I mentioned earlier, all validation rules passed for input, but for image it gives me an error:
The cover must be a file of type: jpeg, jpg, png.
Now, how can I fix it?
I think you should approach this a little differently...
If you instead just create your function like so..
// The Illumniate/Http/Request version of Request in laravel
public function yourFunction(Request $request){
....
$rules = ...;
$validator = Validator::make($request->all(), $rules);
}
The expected format of the Validator is handled automatically because it returns it. And when it runs through you can handle everything the same you already have.
Since this is accepted. The way to actually fix it with the code above is to just remove the multi-dimensional array and just use Input::file('cover') as it returns an array on its own.

Categories