Dynamic Input Array with Image/file in Laravel 8 - php

i am trying to do an update using dynamic for "education history" but there is an image also, i use eloquent to update too, for some reason the data is saved in the database but the image just tmp and cannot find in the folder.
//count array data inputed
for($incs=0; $incs < count($data_detail_user['institution_names']); $incs++) {
// update education
foreach( $data_detail_user['institution_names'] as $key => $file ){
// get old photo thumbnail
$get_photo = Educations::where('id', $key)->first();
// store photo
$path = $file->store(
'assets/education/thumbnail', 'public'
);
$education_user = Educations::find($incs);
$education_user->detail_user_id = $detail_user['id'];
$education_user->name = $data_detail_user['institution_names'][$incs];
$education_user->course = $data_detail_user['education_courses'][$incs];
$education_user->start = $data_detail_user['education_starts'][$incs];
$education_user->graduate = $data_detail_user['education_graduates'][$incs];
$education_user->address = $data_detail_user['education_addresses'][$incs];
$education_user->regencies = $data_detail_user['education_regencies'][$incs];
$education_user->provinces = $data_detail_user['education_provinces'][$incs];
$education_user->country = $data_detail_user['education_countries'][$incs];
$education_user->zip_code = $data_detail_user['education_zips'][$incs];
$education_user->certificate = $data_detail_user['education_certificates'][$incs][$path];
$education_user->save();
$data_detail_user = 'storage/' .$get_photo['certificate'];
if (File::exists($data_detail_user)) {
File::delete($data_detail_user);
} else {
File::delete('storage/app/public/' .$get_photo['certificate']);
}
}
}
[the error show Call to a member function store() on string]
this is the screenshoot of the error
[1]: https://i.stack.imgur.com/l96sm.png

$path = $request->file('path')->store('public/post');
I assume you have a directory where the image is suppose to be stored that's why i created the post directory after public.

Related

laravel Can't delete old image when uploaded new image

why my old image can't be deleted when i uploaded new image?
this is my controller where i use to store data and image.
my file image name is stored combination from nama_post_adps and from $imageName where that is query for getClientOriginalName();
public function update(Request $request, Adopsi $adopsi, $id)
{
$getParentJenisHewan = JenisHewan::where("id", $request->jenis_hewan_id)->value("nama_jenis_hewan");
$getParentRasHewan = RasHewan::where("id", $request->ras_hewan_id)->value("nama_ras_hewan");
$imageSize = $request->file('image_post_adps')->getSize();
$imageName = $request->file('image_post_adps')->getClientOriginalName();
$pathstorage = $request->file('image_post_adps')->storeAs('public/post/adopsi',$request->nama_post_adopsi.'-'.$imageName);
$adopsiAttr = $this->validasiRequest();
$adopsiAttr = $request->all();
$adopsiAttr['nama_jenis_hewan'] = $getParentJenisHewan;
$adopsiAttr['nama_ras_hewan'] = $getParentRasHewan;
$adopsiAttr['image_post_adps'] = $imageName;
$adopsiAttr['path-storage'] = $pathstorage;
$adopsiAttr['size'] = $imageSize;
$adopsi = Adopsi::find($id)->update($adopsiAttr);
$delete = Adopsi::find($id);
unlink('app/public/post/adopsi/'.$delete->nama_post_adopsi.'-'.$delete->image_post_adps);
// if ($request->file('image_post_adps')) {
// Storage::disk('public')->delete('/post/adopsi/'.$request->nama_post_adopsi.'-'.$request->image_post_adps);
// }
if($adopsi) {
return redirect()->route('adopsi.index')->with('success','Data '.$request->nama_post_adopsi .' telah mendapatkan update terbaru.');
} else {
return redirect()->route('adopsi.index')->with('error','Data gagal'.$request->nama_post_adopsi .'diupdate');
}
}
method above literally same with my store method .
i've try unlink() but it can't work and show error : unlink('post/adopsi/..') no such file or directory , but field can't be updated. then i decided use Storage::disk('public')->delete , field got update, the image change with new but old still same.
You are doing wrong.
First fetch existing data and check if request has file then delete old one then update it
$delete = Adopsi::find($id);
if ($request->file('image_post_adps')) {
Storage::disk('public')->delete('/post/adopsi/'.$delete->nama_post_adopsi.'-'.$delete->image_post_adps);
}
$adopsi = Adopsi::find($id)->update($adopsiAttr);

How to upload and save multiple images in database with laravel 5.4?

im trying to upload multiple images with laravel 5.4, actually the process to upload images is done, the question is how to store them in database?
for example when gonna create a slide show of something that has several images that is uploaded, how to group them so the slide show knows those images are in one group?
can you guys help me?
Make sure you go to config/filesystems and turn 'FILESYSTEM_DRIVER' to 'public'
Model to store image paths:
class UserDocuments extends Model
{
//
protected $table = 'user_documents';
public function store($user_id, $document_link, $file_name)
{
$this->user_id = $user_id;
$this->document_link = $document_link;
$this->file_name = $file_name;
$this->save();
}
}
Code in controller to store files ('document' is file input field name)
if ($request->hasFile('document')) {
$link = $request->file('document')->store('documents');
}
$userDocuments->store(request('user_id'), url($link), $link);
To show if the images are in a group, you would have to create a database column called 'group_id' and sort them accordingly.
We have to store images into one records/row by separting commas.
class DocumentController extends Controller
{
public function store(Request $request)
{
$pid = $request->input('pid');
$input = $request->file('files');
$picture = array();
if($request->hasFile('files')) :
foreach ($images as $item):
$extension = $item->getClientOriginalName(); //image extension
$name = time() . '.' .$extension; //image name
$item->move('uploads/documents/', $name); //move to destination
$arr[] = $name; //store image into array
endforeach;
$picture = implode(",", $arr); //Image separated by comma
else:
$picture = '';
endif;
DB::table('document')->insert(array('pid' => $pid,'image' => $picture));
Session::flash('message', 'Multiple Images are uploaded successfully');
return redirect('/multiple-image');
}
}

Laravel retrieve images from database

I need to display the stored images in my view.I've used the below code to store image in db,
$file = Input::file('pic');
$img = Image::make($file);
Response::make($img->encode('jpeg'));
$picture = new Car;
$picture->cartype = Input::get('cartype');
$picture->price = Input::get('price');
$FileName = Input::file('pic')->getClientOriginalName();
$FilePath = public_path('') .'/images/'. $FileName;
$picture->name = $FilePath;
$picture->save();
In my controller( to retrieve image)
public function index()
{
$cars = DB::table('car_category')->get();
return view('category.category',['cars'=>$cars]);
}
How should I retrieve and display the images in view?
If you are storing the image name in the database and uploading it in a directory then you can easily display it by simply fetching the name from database, returning the name to view and append the name to a hard-coded directory address like this -
<img src="/images/{{ $imageVariableName }}">
Let me know if this works.

How to insert Multiple Uploaded files to database

I'm working on a mobile application, and I'm handling database and APIs.
Android developer is sending me images and I'm using file function to get its data.
I have written this code:
public function addalbum($baseurl)
{
$images = array();
if(isset($_FILES['image'])){
//echo "hellow";exit;
//$pathToUpload = '../media/gallary/';
$count = count($_FILES['image']['name']);
//echo $count;exit;
$imagepaths = '';
$imagetepaths = '';
$images = '';
for($i=0;$i<$count;$i++){
$imageurls[$i] = $baseurl."../media/gallary/".$_FILES['image']['name'];
$imagepaths = '../media/gallary/'.$_FILES['image']['name'][$i];
$images[$i] = $_FILES['image']['name'][$i];
$imagetepaths = $_FILES['image']['tmp_name'][$i];
move_uploaded_file($imagetepaths , $imagepaths);
}
}
$data=array(
'image' => ($images != '') ? implode(',',$imageurls) : '',
'email'=>$this->input->post('email'),
'name'=>$this->input->post('name'),
'type'=>$this->input->post('type')
);
//print_r($data);exit;
$this->db->insert('album',$data);
}
But from the bunch of images, only the last one is being inserted in the database.
any help will be very much appreciated.
Thanks
$_FILES['image'] is the field name of 1 uploaded file. If multiple files should be posted you would require different names for each field. Just think how will you upload multiple files from an html form.
For example: $_FILES['image1'], $_FILES['image2'], $_FILES['image3']
You could use something like this:
if(is_array($_FILES)) {
foreach($_FILES as $fileKey => $fileVal){
if($fileVal[name]) {
move_uploaded_file($_FILES["uploaded_file"]["tmp_name"],$target_path.$fileVal[name]);
}
}
}
Checkout this example where a maximum of 3 files are uploaded from android using php.

save and display for files in user profile in Moodle

I'm trying to create a moodle profile field plugin for file upload.
my edit_field_add in field.class is:
function edit_field_add(&$mform) {
$maxlength = 1024*1024;
$fieldtype = $this->field->param2;
/// Create the form field
$mform->addElement('filepicker', $this->inputname, format_string($this->field->name), null,
array('maxbytes' => $maxlength, 'accepted_types' => $fieldtype));
$mform->setType($this->inputname,PARAM_FILE);
}
This shows and saves file correctly but
Saves a number in data field of plugin (e.g. 766686554)
How can I find the URL to the uploaded file to make a link to it by display_data in 'field.class` ?
EDIT
I'm saving the file by this:
function edit_save_data_preprocess($data, &$datarecord) {
$draftitemid=file_get_submitted_draft_itemid($this->inputname);
if (empty($entry->id)) {
$entry = new stdClass;
$entry->id = 0;
}
$context = context_user::instance($this->userid);
file_save_draft_area_files($draftitemid, $context->id, 'profile_field_fileupload', $this->inputname,$entry->id);
return $draftitemid;
}
But draft still exists and I cant find how to retrieve saved file!
Assuming you have saved the file after the form has been posted -http://docs.moodle.org/dev/Using_the_File_API_in_Moodle_forms#filepicker
Then you can use the File API to retrieve the file(s) - http://docs.moodle.org/dev/File_API#Serving_files_to_users
eg to display links to all files for the plugin:
$out = array();
$fs = get_file_storage();
$files = $fs->get_area_files($contextid, $pluginname, $pluginfolder);
foreach ($files as $file) {
$filename = $file->get_filename();
$url = moodle_url::make_file_url('/pluginfile.php', array(
$file->get_contextid(),
$pluginname,
$pluginfolder,
$file->get_itemid(),
$file->get_filepath(), $filename)
);
$out[] = html_writer::link($url, $filename);
}
$br = html_writer::empty_tag('br');
echo implode($br, $out);

Categories