Image upload in database - NULL (OOP) - php

Profile image won't upload in database. It get's uploaded in folder, but in database it just says NULL.
Code:
if (Input::exists()) {
if (Token::check(Input::get('token'))) {
try {
$user->update(array(
'image' => $title
));
if (isset($_FILES["image"])) {
$title = date("dmyHms") . "_" . $_FILES["image"]["name"];
$path = "img/profile/" . $_POST["id"] . "_" . $title;
move_uploaded_file($_FILES["image"]["tmp_name"], $path);
}
} catch (Exception $e) {
die($e->getMessage());
}
}
}
Form:
This is solution, it saves image in database:
$user->update(array(
'image' => 'image',
'image' => $title
));

Related

upload image with other form values using along via REST api with laravel

I'm working on a project which requires uploading of images and whiles uploading I want to send some values as well to the API. I'm currently running a test with postman, the image upload works fine but I'm finding it hard to grab the values sent alongside
public function newUpload($profileId, Request $request)
{
try {
if (!$request->hasFile('image')) {
return response()->json(['upload_file_not_found'], 400);
}
$file = $request->file('image');
if (!$file->isValid()) {
return response()->json(['invalid_file_upload'], 400);
}
$path = public_path() . '/uploads';
$defaultDateTime = strtotime(date('Y-m-d H:i:s'));
$rename = "_test" . rand(0, 1000000000) . $profileId . $defaultDateTime . '.' .
$file->getClientOriginalExtension();
$file->move($path, $rename);
$workDays = $request->payload->get('workDays');
if ($workDays) {
foreach ($workDays as $day) {
$data[] = [
'profile_id' => $profileId,
'name' => $day['name'],
'vdate' => $request->payload->tDateTime,
];
}
DB::table('workDays')->insert($data);
}
} catch (Exception $e) {
dd($e->getMessage());
}
}
When you are trying to access the workDays element you are trying to access a JSON string not a JSON object.
You can get around this by getting the payload from the Request object and then json_decode the string.
$payload = json_decode($request->payload, true, 512, JSON_THROW_ON_ERROR);
if ($payload['workDays']) {
foreach ($payload['workDays'] as $day) {
$data[] = [
'profile_id' => $profileId,
'name' => $day['name'],
'vdate' => $payload['tDateTime'],
];
}
}

Magento set image on store view

Problem
I'm working on an integration with Magento which first removes all images from a product and then add new ones. The problem is that when I add them the 'thumbnail', 'small_image' and 'image' only gets set on the default store and not the individual stores.
Code
public function setProductImages($entityId, $images, $websiteIds, $removeFirst = true){
$product = Mage::getModel('catalog/product')->load($entityId);
if($removeFirst){
//First I need to reset image selection before I can remove all images
$values = array(
'image' => 'no_selection',
'small_image' => 'no_selection',
'thumbnail' => 'no_selection'
);
//Go through all sites and stores and set the image selection values
foreach($websiteIds as $websiteId) {
$website = Mage::getModel('core/website')->load($websiteId);
foreach ($website->getStoreIds() as $storeId) {
Mage::getSingleton('catalog/product_action')->updateAttributes(array($product->getId()), $values, $storeId);
}
}
//Set the selection values on admin store
Mage::getSingleton('catalog/product_action')->updateAttributes(array($product->getId()), $values, 0);
//Remove all images on product
$mediaGalleryAttribute = Mage::getModel('catalog/resource_eav_attribute')->loadByCode($product->getEntityTypeId(), 'media_gallery');
$gallery = $product->getMediaGalleryImages();
foreach ($gallery as $galleryImage) {
$imageFile = $galleryImage->getFile();
$mediaGalleryAttribute->getBackend()->removeImage($product, $imageFile);
}
$product->save();
}
foreach($images as $image) {
file_put_contents($path . DS . $image->filename, $image->content);
$type = in_array($image->name, array('image', 'small_image', 'thumbnail')) ? $image->name : null;
$product->addImageToMediaGallery($path . DS . $image->filename, $type, true, false);
}
$product->save();
}
Is there some way to tell addImageToMediaGallery to set on an array of stores? Or am I missing something?
Solved it by replacing
foreach($images as $image) {
file_put_contents($path . DS . $image->filename, $image->content);
$type = in_array($image->name, array('image', 'small_image', 'thumbnail')) ? $image->name : null;
$product->addImageToMediaGallery($path . DS . $image->filename, $type, true, false);
}
$product->save();
with this:
$imageTypes = array();
//Sets images on default store for product
foreach($images as $image){
file_put_contents($path . DS . $image->filename, $image->content);
$type = in_array($image->name, array('image', 'small_image', 'thumbnail')) ? $image->name : null;
$product->addImageToMediaGallery($path . DS . $image->filename, $type, true, false);
//Store image, small_image and thumbnail for later use
$imageTypes['image'] = $product->getImage();
$imageTypes['small_image'] = $product->getSmallImage();
$imageTypes['thumbnail'] = $product->getThumbnail();
}
$product->save();
//Go through all stores and set image, small_image and thumbnail
foreach($websiteIds as $websiteId) {
$website = Mage::getModel('core/website')->load($websiteId);
foreach($website->getStoreIds() as $storeId) {
Mage::app()->setCurrentStore($storeId);
Mage::getSingleton('catalog/product_action')->updateAttributes(array($product->getId()), $imageTypes, $storeId);
}
}
$product->save();

update a record without removing the uploaded file in yii

I need to UPDATE record with out changing or deleting filename(i mean file) , OR reinsert file again so how i can do this?
here is my actionCreate, How i can write update?
public function actionCreate() {
$model = new Page;
if (isset($_POST['Page'])) {
$model->attributes = $_POST['Page'];
$model->filename = CUploadedFile::getInstance($model, 'filename');
if ($model->save()) {
if ($model->filename !== null) {
$dest = Yii::getPathOfAlias('application.uploads');
$model->filename->saveAs($dest . '/' . $model->filename->name);
$model->save();
}
$this->redirect(array('view', 'id' => $model->id));
}
}
$this->render('create', array(
'model' => $model,
));
}
So Please can anyone find a solution
If you don't need to change or delete filename in edit/update then ignore filename (and upload part) assuming the file is alrready uploaded and you don't wish to change/delete it.
public function actionUpdate($id) {
$model = $this->loadModel($id);
$file = $model->filename;
if (isset($_POST['Page'])) {
$model->attributes = $_POST['Page'];
$model->filename = $file;
if ($model->save()) {
$this->redirect(array('view', 'id' => $model->id));
}
}
$this->render('create', array(
'model' => $model,
));
}
Try this, it's working for me -
create a upload folder outside protected directory and also give read/write permission.
actionCreate function -
public function actionCreate() {
$model = new Page();
if(isset($_POST['Page']) && !empty($_POST['Page'])){
$model->attributes = $_POST['Page'];
$rand = rand(1, 999);
$myfile = CUploadedFile::getInstance($model, 'filename');
$fileName = "{$rand}-{$myfile}"; //Generate unique file name
if(!empty( $fileName)){
$model->filename = $fileName;
$target_dir = realpath( Yii::getPathOfAlias('application') . '/../upload');
$target_file = $target_dir . '/' . $fileName;
if(!$myfile->saveAs($target_file)){
$model->addError('filename', 'File saving error');
}
}
if(!$model->hasErrors() && $model->validate() && $model->save(false)) {
$this->redirect(array('view', 'id'=>$model->id, 'msg'=>'success'));
}
}
}
actionUpdate function -
public function actionUpdate() {
$model = Page::model()->findbyPK($id);
$model->scenario = 'update';
if(isset($_POST['Page']) && !empty($_POST['Page'])){
$model->attributes = $_POST['Page'];
if(empty($_POST['Page']['filename'])) { $file_name = $model->filename; } //store existing file name into a variable if your uploading a file on update
$rand = rand(1, 999);
$myfile = CUploadedFile::getInstance($model, 'filename');
$fileName = "{$rand}-{$myfile}"; //Generate unique file name
if($model->validate()) {
if(!empty($fileName)) {
$model->filename = $fileName;
$target_dir = realpath( Yii::getPathOfAlias( 'application' ) . '/../upload');
$target_file = $target_dir . '/' . $fileName;
if(!$myfile->saveAs($target_file)){
$model->addError('filename', 'File saving error');
}
}
else {
$model->filename = $file_name; //allow existing file name
}
if( !$model->hasErrors() && $model->save(false) ) {
$this->redirect(array('view', 'id'=>$model->id, 'msg'=>'update'));
}
}
}
In model rules array define this -
array('filename', 'file', 'types'=>'jpg, jpeg, bmp, gif, png', 'allowEmpty'=>true, 'on'=>'insert, update')

add action fails for value of imagepath

In my database I have a varchar field to save the path include the name of an imagefile. In my viewscript I also use this field. If I insert for a test a pathname in my database via phpadmin everything works fine.
If I use my Controller addAction I can´t save the path, without error.
Here is my addAction:
$form = new Application_Form_Buch();
$form->submit->setLabel('Add');
$this->view->form = $form;
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
$autor = $form->getValue('autor');
$verlag = $form->getValue('verlag');
$titel = $form->getValue('titel');
if( $form->getElement('datei')->receive() <> 1)
{
echo ' filename: '. $form->getElement('datei')->receive();
$imagepath = $form->getElement('datei')->getFileName();
//echo ' filename: '. $form->getElement('datei')->getFileName();
$pathparts = pathinfo($form->getElement('datei')->getFileName());
//echo ' pathparts: '. $pathparts;
//then get the part that you want to use
$originalFilename = $pathparts['basename'];
//echo ' originalFilename: '. $originalFilename;
//echo ' Test basename: '. $originalFilename['basename'];
$form->getElement('datei')->addFilter('Rename','images' ); //'/images/upload/',$originalFilename
//rename funktioniert so nicht
$originalFilename = $pathparts['basename'];
$imagepath=$form->getElement('datei')->getFileName();
$imagepath = str_replace($imagepath, "/images/cover/".$originalFilename, $imagepath); //funktioniert !!!
//echo ' imagepath: '. $imagepath;
$books = new Application_Model_DbTable_Bibliothek();
$books->addBook( $autor, $titel, $verlag, $imagepath );
}
else{
$imagepath=NULL;
}
// $this->_helper->redirector('index');
} else {
$form->populate($formData);
}
}
Please don´t mind I tried a bit around, so I have some comments left. I tested the variable $imagepath and it delivers the wanted value, which is: /images/cover/imagename.jpg. Where is the error in this pathvalue?
And here is my add Function which I use to store in my database:
public function addBook($autor, $titel, $verlag, $pfad)
{
$data = array(
'autor' => $autor,
'titel' => $titel,
'verlag' => $verlag,
'pfad' => $pfad,
);
$this->insert($data);
}
It works quite fine, it saves all comming data instead of the $pfad variable.
NEW:
must be something with the format of $imagepath, I just added for testing: $imagepath= '/images/cover/Labyrinth_200.jpg'; and find the value in my database table. So the error should be in the format of getting the value of $imagepath.
I just found my (very stupid) error.
I changed the blocks in my control structure like following:
if( $form->getElement('datei')->receive() <> 1)
{
$imagepath=NULL;
}
else{
echo ' filename: '. $form->getElement('datei')->receive();
$imagepath = $form->getElement('datei')->getFileName();
//echo ' filename: '. $form->getElement('datei')->getFileName();
$pathparts = pathinfo($form->getElement('datei')->getFileName());
//echo ' pathparts: '. $pathparts;
//then get the part that you want to use
$originalFilename = $pathparts['basename'];
//echo ' originalFilename: '. $originalFilename;
//echo ' Test basename: '. $originalFilename['basename'];
$form->getElement('datei')->addFilter('Rename','images' ); //'/images/upload/',$originalFilename
//rename funktioniert so nicht
$originalFilename = $pathparts['basename'];
$imagepath=$form->getElement('datei')->getFileName();
$imagepath = str_replace($imagepath, "/images/cover/".$originalFilename, $imagepath); //funktioniert !!!
//echo ' imagepath: '. $imagepath;
}
//$imagepath= '/images/cover/Labyrinth_200.jpg';
$books = new Application_Model_DbTable_Bibliothek();
$books->addBook( $autor, $titel, $verlag, $imagepath );
Before that I tried if( $form->getElement('datei')->receive() = 1) to validate my condition. But I got an error. So I switched the two blocks and now it works.

Only update image if user uploaded a new one, Laravel

I have an edit form which has an image field where a user can upload a new image if he wants to.
But if the user does not upload a new photo I don't want to validate the image field and just use the photo that's already in the database. And not update the image field at all.
Here is my edit function:
public function postEdit($id) {
$product = Product::find($id);
// This should be in product model, just testing here
$edit_rules = array(
'category_id' => 'required|integer',
'title' => 'required|min:2',
'description' => 'required|min:10',
'price' => 'required|numeric',
'stock' => 'integer'
);
// Add image rule only if user uploaded new image
if (Input::has('image')) {
$edit_rules['image'] = 'required|image|mimes:jpeg,jpg,bmp,png,gif';
}
$v = Validator::make(Input::all(), $edit_rules);
if ($product) {
if ($v->fails()) {
return Redirect::back()->withErrors($v);
}
// Upload the new image
if (Input::has('image')) {
// Delete old image
File::delete('public/'.$product->image);
// Image edit
$image = Input::file('image');
$filename = date('Y-m-d-H:i:s')."-".$image->getClientOriginalName();
Image::make($image->getRealPath())->resize(600, 600)->save('public/img/products/'.$filename);
$product->image = 'img/products/'.$filename;
$product->save();
}
// Except image because already called save if image was present, above
$product->update(Input::except('image'));
return Redirect::to('admin/products')->with('message', 'Product updated.');
}
return Redirect::to('admin/products');
}
Using this I can update all the values except the image.
If I don't upload a new photo it saves all other updated values.
If I do upload a new photo it just ignores it and saves all other updated values, doesn't upload the new photo.
Check if the request has the file:
public function update(Request $request)
{
// Update the model.
if($request->hasFile('photo')) {
// Process the new image.
}
// ...
}
public function update() {
$id=Input::get('id');
$rules= array('name'=>'required|regex:/(^[A-Za-z]+$)+/',
'detail'=>'required|regex:/(^[A-Za-z]+$)+/',
'images' => 'required|image');
$dat = Input::all();
$validation = Validator::make($dat,$rules);
if ($validation->passes()){
$file =Input::file('images');
$destinationPath = 'image/pack';
$image = value(function() use ($file){
$filename = date('Y-m-d-H:i:s') . '.' . $file->getClientOriginalExtension();
return strtolower($filename);
});
$newupload =Input::file('images')->move($destinationPath, $image);
DB::table('pkgdetail')
->where('id', $id)
->limit(1)
->update(array('name' => Input::get('name'), 'detail' => Input::get('detail'), 'image' => $newupload));
$data=PackModel::get_all();
return View::make('pkg_dis')->with('data',$data)
->withErrors($validation)
->with('message', 'Successfully updated.');
}
}
use Illuminate\Support\Facades\Input;
public function update(Request $request, $id)
{
if ($tag = Tag::find($id))
{
$this->validate($request, [
'tag_name' => 'required|min:3|max:100|regex: /^[a-zA-Z0-9\s][a-zA-Z0-9\s?]+$/u|unique:tags,tag_name,'.$id.',id',
]);
$tag->tag_name=$request->input('tag_name');
// get the image tag_img_Val
if($request->hasFile('tag_image'))
{
$this->validate($request, [
'tag_image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:1000',
]);
$img = $request->file('tag_image');
$old_image = 'uploads/' . $tag->tag_image;//get old image from storage
if ($img != '')
{
$image = rand() . '_' . ($img->getClientOriginalName());
$path = 'uploads/';
//Storing image
if ($img->move(public_path($path), $image))
{
$tag->tag_image = $image;
if ($tag->update())
{
if (is_file($old_image)) {
unlink($old_image); // delete the old image
}
return response()->json(['message' => 'Tag has been updated successfully.'],200);
}
else
{
unlink($image); // delete the uploaded image if not updated in database
return response()->json(['message' => "Sorry, Tag not updated"],500);
}
}
else
{
return response()->json(['message' => "Sorry, Image not moved"],500);
}
}
else
{
return response()->json(['message' => "Sorry, Image not uploaded"],500);
}
}
else
{
if($tag->update(Input::except('tag_image')))
{
return response()->json(['message' => 'Tag has been updated successfully.'],200);
}
else
{
return response()->json(['message' => "Sorry, Tag not updated"],500);
}
}
}
else
{
return response()->json(['message' => 'Tag not found'], 404);
}
}
You need to use multipart for form enctype
You can use another function to delete the images from the folder. like here
private function unlinkPostImages($images)
{
if(!empty($images)){
foreach ($images as $img){
$old_image = public_path('storage/' . $img->image);
if (file_exists($old_image)) {
#unlink($old_image);
}
}
}
}
Then call this function above image delete function. like this...
$this->unlinkPostImages($getId->images); // this will delete image from folder
$getId->images()->delete(); // --> this delete from database table $post->id
same this Click here..
my update function
public function update(UpdatePostRequest $request, Post $post)
{
//
$data = $request->only(['title', 'description', 'contents', 'price']);
// صورة الإعلان //
if ($request->hasFile('image')) {
Storage::disk('public')->delete($post->image);
$imagePath = $request->image;
$filename = Str::random(10).'-'.time().'-'.$imagePath->getClientOriginalName();
$image_resize = Image::make($imagePath->getRealPath());
$image_resize->fit(120);
$image_resize->orientate();
$image_resize->save(public_path('storage/images/' .$filename), 100);
$sImg = 'images/'. $filename;
$data['image'] = $sImg;
}
// -------- //
if ($request->hasFile('images'))
{
$getId = Post::find($post->id);
$this->unlinkPostImages($getId->images);
$getId->images()->delete();
$uploadPicture = array();
foreach ($request->file('images') as $photo) {
$file = $photo;
$filename = $file->getClientOriginalName();
$picture = date('His').'-'.$filename;
$file->move(public_path('storage/images/'), $picture);
array_push($uploadPicture, new PostImages(array('image' => 'images/'. $picture)));
}
$post->images()->saveMany($uploadPicture);
}
if ($request->input('contents')) {
$data['content'] = $request->contents;
}
//dd($data);
$post->update($data);
session()->flash('SUCCESS', 'تم تحديث الإعلان بنجاح.');
return redirect()->route('post.show', [$post->id, Post::slug($post->title)]);
}
In controller part:
$destinationPath = 'uploads';
$extension = Input::file('image')->getClientOriginalExtension();
var_dump($extension);
$fileName = rand(11111,99999).'.'.$extension;
Input::file('image')->move($destinationPath, $fileName);

Categories