I am trying to update an image and other data in a database, but when I update only text data, the image value becomes null or empty.
<form action="/admin/settings/why-us/update/{{$data->id}}" enctype="multipart/form-data" method="POST">
#csrf
<input type="text" class="form-control" name="title" value="{{$data->title}}">
<input type="file" class="form-control" value="{{$data->image}}" name="image">
<button type="submit" class="btn btn-success py-2 px-4 text-white">Update changes</button>
</form>
This a controller
public function updateWhyusPageSetting(Request $request,$id)
{
$title = $request->input('title');
$image = $image = $request->file('image');
dd($image);
if($request->hasFile('image')) {
$image = $request->file('image');
$filename = $image->getClientOriginalName();
$image->move(public_path('/frontend/images/'), $filename);
$image_upload = $request->file('image')->getClientOriginalName();
}
DB::table('features')
->where('id', $id)
->update([
'title' => $title,
'image' => $image_upload
]);
\Session::flash('flash_message', __('Why us data updated'));
\Session::flash('flash_type', 'success');
return redirect()->back();
}
When I input only the title, left out the image, and tried to dump using dd($image);, I got a null value.
When updating the image, it's getting updated very well database.
Now, my question is, how do I make sure the value is captured in the input file <input type="file" class="form-control" value="{{$data->image}}" name="image"> so that when I update other data, it also sends the image value. NB: value="{{$data->image}}" IS NOT capturing the data from database
Try this code
public function updateWhyusPageSetting(Request $request,$id){
$data = [];
$data['title'] = $request->input('title');
if($request->hasFile('image')) {
$image = $request->file('image');
$image->move(public_path('/frontend/images/'),$imageName = $image->hashName()); //hashName() will generate image name with extension
$data['image'] = $imageName; // here if user uploads an image, it will add to data array then add to DB.
}
DB::table('features')
->where('id', $id)
->update($data); // if a user uploaded an image will add. if not, a previous image will not change
\Session::flash('flash_message', __('Why us data updated'));
\Session::flash('flash_type', 'success');
return redirect()->back();
}
Please note you should delete the old images if you don't need anymore
you can use this to delete an old image if you want
(new Filesystem())->delete("full/path/with/image/name.jpg");
Related
I'm trying to upload image-file from frontend in OctoberCMS
I have a model Person and relation:
public $attachOne = [
'photo' => 'System\Models\File'
];
In php-block with upload form:
public function onUploadImage() {
$person = Person::where('id', '=', $this->param('id'))->first();
$person->photo = \Input::file('avatar');
$person->save();
}
And my template:
<form method="POST" action="/persons/person/{{person.id}}" accept-charset="UTF-8" enctype="multipart/form-data">
<input type="hidden" name="_handler" value="onUploadImage">
<input type="file" name="avatar" id="avatar" />
{{ form_token() }}
{{ form_sessionKey() }}
<button type="submit" data-attach-loading>Upload</button>
After submit it saves to DB only path 'http://my-site/storage/app/uploads/public/' and does not upload any files to filesystem. It seems like there are no some permissions, but I can easily upload images from backend.
Where is my error?
You must get the UploadedFile from the request and store it to one of the configured disks. And store the path to the image in the database.
Assume storage/app/public/images is the directory where the uploaded images should be stored.
public function onUploadImage() {
if(request()->hasFile('avatar') && request()->file('avatar')->isValid()) {
$file = request()->file('avatar');
$filename = $file->getClientOriginalName();
$person = Person::where('id', '=', $this->param('id'))->first();
$person->photo = $file->storeAs('images', $filename)
$person->save();
}
}
Here is the solution.
if(request()->hasFile('avatar') && request()->file('avatar')->isValid()) {
$file = new System\Models\File;
$file->data = Input::file('avatar');
$file->is_public = true;
$file->save();
$person = Person::where('id', '=', $this->param('id'))->first();
$person->photo()->add($file);
$person->save();
}
//Here is my edit form (image field)
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 want to just use the photo that's already in the database. And not update the image field at all. But in my code whenever I am trying to without uploading new image form is not taking the old input value.
<div class="form-group">
<input type="file" name="image">
</div>
//this is the update function
public function update(Request $request, $id)
{
$this->validate($request,[
'name' => 'required',
'image' => 'mimes:jpeg,bmp,png,jpg'
]);
// get form image
$image = $request->file('image');
$slug = str_slug($request->name);
$category = Category::find($id);
if (isset($image))
{
// make unique name for image
$currentDate = Carbon::now()->toDateString();
$imagename = $slug.'-'.$currentDate.'-'.uniqid().'.'.$image->getClientOriginalExtension();
// check category dir is exists
if (!Storage::disk('public')->exists('category'))
{
Storage::disk('public')->makeDirectory('category');
}
// delete old image
if (Storage::disk('public')->exists('category/'.$category->image))
{
Storage::disk('public')->delete('category/'.$category->image);
}
// resize image for category and upload
$categoryimage = Image::make($image)->resize(1600,479)->stream();
Storage::disk('public')->put('category/'.$imagename,$categoryimage);
// check category slider dir is exists
if (!Storage::disk('public')->exists('category/slider'))
{
Storage::disk('public')->makeDirectory('category/slider');
}
// delete old slider image
if (Storage::disk('public')->exists('category/slider/'.$category->image))
{
Storage::disk('public')->delete('category/slider/'.$category->image);
}
// resize image for category slider and upload
$slider = Image::make($image)->resize(500,333)->stream();
Storage::disk('public')->put('category/slider/'.$imagename,$slider);
} else {
$imagename = $category->image;
}
$category->name = $request->name;
$category->slug = $slug;
$category->image = $imagename;
$category->save();
Toastr::success('Category Successfully Updated :)' ,'Success');
return redirect()->route('admin.category.index');
}
// When i click on the edit button it shows the No file Chosen it is not displaying the old image ..
you should change your validation
in STORE function, you should give an image and upload it (if it is required)
but in UPDATE function maybe the user does'nt want to change image and user only wants to change for exmaple just the name, so user can select no image in update
so your validation in UPDATE must be NULLABLE.
$this->validate($request,[
'name' => 'required',
'image' => 'nullable|mimes:jpeg,bmp,png,jpg'
]);
I need to validate my image array as an image and specific image file extensions only. but my request validation to image WONT ALLOW me to use inser nullable values
For example I will add a content and dont want to add images. then the image should contain null that is why i need to have request validation as nullable. But in my experience null value is not allowed and it gives me error why? help me please
here is the error.
Undefined variable: promotion
here is my CONTROLLER
public function store(Request $request)
{
$this->validate($request, [
'promotion_image' => 'image|nullable|max:1999'
]);
if ($request->has('promotion_image'))
{
//Handle File Upload
$promotion = [];
foreach ($request->file('promotion_image') as $key => $file)
{
// Get FileName
$filenameWithExt = $file->getClientOriginalName();
//Get just filename
$filename = pathinfo( $filenameWithExt, PATHINFO_FILENAME);
//Get just extension
$extension = $file->getClientOriginalExtension();
//Filename to Store
$fileNameToStore = $filename.'_'.time().'.'.$extension;
//Upload Image
$path = $file->storeAs('public/promotion_images',$fileNameToStore);
array_push($promotion, $fileNameToStore);
}
$fileNameToStore = serialize($promotion);
}
else
{
$fileNameToStore='noimage.jpg';
}
if (count($promotion)) {
$implodedPromotion = implode(' , ', $promotion);
$promotionImage = new Promotion;
$promotionImage->promotion_image = $implodedPromotion;
$promotionImage->save();
return redirect('/admin/airlineplus/promotions')->with('success', 'Image Inserted');
}
return redirect('/admin/airlineplus/promotions')->with('error', 'Something went wrong.');
}
here is my VIEW
{!! Form::open(['action'=>'Admin\PromotionsController#store', 'method' => 'POST','enctype'=>'multipart/form-data', 'name' => 'add_name', 'id' => 'add_name']) !!}
<div class="form-group">
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td> {{ Form::file('promotion_image[]')}}</td>
<td>{{ Form::button('', ['class' => 'btn btn-success fa fa-plus-circle', 'id'=>'add','name'=>'add', 'style'=>'font-size:15px;']) }}</td>
</tr>
</table>
{{Form::submit('submit', ['class'=>'btn btn-primary', 'name'=>'submit'])}}
</div>
</div>
{!! Form::close() !!}
You need to declare $promotion = [] above if ($request->has('promotion_image')), not inside of it.
So:
public function store(Request $request)
{
$this->validate($request, [
'promotion_image' => 'image|nullable|max:1999'
]);
$promotion = [];
if ($request->has('promotion_image'))
{
//Handle File Upload
That is because your selecting file other than image in your form. See the following to restrict user to only upload images.
<input accept=".png, .jpg, jpeg" name="files[]" type="file" multiple>
Not sure but try once
'promotion_image' => 'nullable|mimes:jpeg,jpg,png,gif|max:1999'
I tried to upload file images into mysql using Codeigniter
This is likely my upload view:
<label>Upload File</label>
<input type="file" class="form-control" name="images">
</div>
I've done with image name, description, etc.
I tried to save it into database, just like normal input form.
The result, column "images" cannot be null. I have set column "images" with varbinary(3000)
Am I doing it wrong?
EDITED:
My Controller:
public function save(){
$this->gallery_model->save_foto();
$this->session->set_flashdata('msg','FOTO BERHASIL DI UPLOAD');
redirect(base_url('gallery'));
}
My Model
<?php
class Gallery_model extends CI_Model {
public function __construct() {
parent::__construct();
}
public function save_foto(){
$data['id'] = date('U');
$data['nm_foto'] = $this->input->post('nm_foto');
$data['username'] = $this->input->post('username');
$data['tanggal'] = date('j F Y');
$data['images'] = $this->input->post('images');
$data['deskripsi'] = $this->input->post('deskripsi');
$this->db->insert( 'gallery', $data );
}
}
You can't directly upload image into database , Insert image path
For upload image form form add
enctype="multipart/form-data"
in form .
For more help regarding image upload in codeigniter
Codeigniter Image Upload
You can store images but its not advisable.
The "correct" way to do it is to store the files somewhere on your server and store the URI in the database.
The problem is that images can be quite large, this can result in a big load on your database which is unnecessary. When you work on a larger scale project you may have multiple database that need to be synchronised, when you database is larger then it need to be you unnecessary slow down your network.
If you still want the image stored in the datebase, you can store it as an BLOB type. See the MySQL documenation
You can insert it then with the following example code
$data['image'] = file_get_contents($_FILES['image']['tmp_name']);
If someone met an error and getting tired just like me, here's the simple way and codes you can upload [images] into your assets folder
In Controller
public function upd_gallery(){
$file = $this->input->post('img_name').".jpg";
move_uploaded_file($_FILES['images']['tmp_name'], './wheretosave/etc/etc'.$file);
redirect( base_url().'gallery');
}
Set application -> config -> routes
$route['gallery/upload2'] = 'gallery/upd_gallery';
Put this to your view
<?php
$ff = './where-to-save/etc/'.$this->input->post('img_name').'.jpg';
?>
<form action="<?= base_url()?>gallery/upload2" method="post" enctype="multipart/form-data">
<div class="form-group">
<input type="text" class="form-control" name="img_name" required="required">
</div>
<div class="form-group">
<input type="file" class="form-control" name="images">
</div>
<div class="form-group">
<button type="submit" class="btn btn-common" value="Update"> Upload</button>
</div>
</div>
</div>
Of course, this way is very simple. You just have to name your image and save it
Saving image in database is NOT good practice. You can use following code to store files on your server's file system.
$userfile= $this->input->post('userfile'); //gets image name only
if ($_FILES['userfile']['name'] != '') { //to check if you've selected any file
$path = './path/to/folder';
$config['overwrite'] = FALSE;
$config['encrypt_name'] = FALSE;
$config['remove_spaces'] = TRUE;
$config['upload_path'] = $path;
$config['allowed_types'] = 'jpg|png|gif|jpeg';
$config['max_size'] = '0';
if (!is_dir($config['upload_path']))
die("THE UPLOAD DIRECTORY DOES NOT EXIST");
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile')) {
return "UPLOAD ERROR ! " . $this->upload->display_errors();
}
else {
$filepath = $this->upload->data();
$doc_path = $filepath['file_name'];
return $doc_path;
}
}
I am trying to edit/update my image upload but I am getting "Call to a member function getClientOriginalExtension() on a non-object" error. please help
My controller:
public function update(Request $request, $id)
{
$lnkupdate=Request::all();
$links=Links::findorFail($id);
$file = Input::file('image');
$random_name = str_random(8);
$destinationPath = 'albums/';
$extension = $file->getClientOriginalExtension();
$filename=$random_name.'_link_logo.'.$extension;
$uploadSuccess = Input::file('image')->move($destinationPath, $filename);
ConsularGen::update(array(
'name'=>Input::get('name'),
'link' => Input::get('link'),
'image' => $filename,
));
}
View:
{!!Form::model($links,['method'=>'PATCH','action'=>['LinksController#update',$links->id]])!!}
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label for="image">Select a logo</label>
{!!Form::file('image')!!}
</div>
<div class="form-goup">
{!!Form::label('name','Name')!!}
{!!Form::text('name',null,['class'=>'form-control'])!!}
</div>
<div class="form-goup">
{!!Form::label('link','Link')!!}
{!!Form::text('link',null,['class'=>'form-control'])!!}
</div>
<div class="form-group">
<button type="submit" class="btnbtn-default">Add</button>
</div>
{!!Form::close()!!}
Route:
Route::patch('admin/links/{id}/update','LinksController#update');
Uploading files requires the html form to specify enctype="multipart/form-data". If you don't have this, the file will not be uploaded, Input::file('image') will return null, and you'll get the error you're seeing.
The Laravel Form builder will add this to your form if you tell it that it needs to handle files. Add 'files' => true to your array in the form:
{!! Form::model($links, ['method'=>'PATCH', 'files' => true, 'action'=>['LinksController#update', $links->id]]) !!}
Once this is fixed, you'll also get this error if you don't actually select a file to be uploaded. You should wrap your file handing inside a check to hasFile. Something like:
public function update(Request $request, $id)
{
$lnkupdate=Request::all();
if (Input::hasFile('image')) {
$links=Links::findorFail($id);
$file = Input::file('image');
$random_name = str_random(8);
$destinationPath = 'albums/';
$extension = $file->getClientOriginalExtension();
$filename=$random_name.'_link_logo.'.$extension;
$uploadSuccess = Input::file('image')->move($destinationPath, $filename);
ConsularGen::update(array(
'name'=>Input::get('name'),
'link' => Input::get('link'),
'image' => $filename,
));
} else {
echo 'no file uploaded. oops.';
}
}
Your file has not uploaded successfully.
you are trying to run getClientOriginalExtension() on a null file thats's why you are getting this error