How to upload multiple image in laravel php - php

i am trying to upload multiple images in laravel, but it seems only one image in inserted into the database and i was wondering how can i be uploading all images not just one.
here is my controller
public function addProperty(Request $request){
$data = $request->all();
$pModel = new PropertyModel();
return response()->json(["type"=>$pModel->addProperty($data,$request)]);
}
here is my view
<h3>Gallery</h3>
<div class="submit-section">
<div id="selected-files"></div>
<input type="file" name="files[]" multiple onchange="Property.onImageUploadChange(event)" id="files" >
</div>
here is my model
public function addProperty($propertyData,$request){
$db = new Database;
#session_start();
$user = $_SESSION["user"];
$propertyData["user_id"] = $user->user_id;
unset($propertyData["_token"]);
unset($propertyData["property_files"]);
$res = $db->query($db->buildQuery($propertyData, $this->tableName)) or die(false);
$lastID= $db->lastInsertID($res);
$image = $request->file("property_files");
$image->move(public_path('images'),$lastID.".jpg");
return true;
}

may this code help you!
I'm work on backend and use this function:
public static function upload_image($image, $image_folder)
{
$image_new_name = time() . '_' . $image->getClientOriginalName();
$image_path = public_path('uploads\\' . $image_folder);
$image->move($image_path, $image_new_name);
return $image_folder . '/' . $image_new_name;
}
you can create a SettingController and put it there, then in your controller receive array of images and with foreach loop save them in your server like:
foreach($request->arrayImages as $image) {
SettingController::upload_image($image, 'your folder name');
}

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);

Looking for Laravel php developer to resolve updating function with image uploading its not working

It's my update function and it's not showing image when I echo $fileName. It's not working like it was I want to make it with the condition if there is any image then update that image otherwise leave that I tried many times but it's not working.
public function update(Request $request, Header $header)
{
if($request->hasFile('headerimg')){
$fileName = $request->file('headerimg')->getClientOriginalName();
$request->file('headerimg')->move('uploads/header',$fileName);
}
$header->title = $request->title;
$header->discription = $request->discription;
$header->keywords = $request->keywords;
$header->headerimg = $fileName;
$header->h2 = $request->h2;
$header->breadcumb = $request->breadcumb;
$header->category = $request->category;
$header->save();
return redirect()->route('dashboard.headers.index')->with('success', 'Packages Edited Successfully');
}
I guess that your problem is in your view.
Maybe you forget to use enctype="multipart/form-data" or your input name does not match with mapped controller variable.
For find the exact problem use dd($request) and dd($request->file('headerimg')) and see can you get request correct or not.
I use this code edit image and if image was not selected the old image will remain same without any error.
public function update(Request $request, Header $header)
{
$file = $request->headerimg;
$id = $request->id;
if($file == ''){
$arr['header'] = Header::select()->where($id);
$fileName = $header['headerimg'];
}
else{
$fileName = $request->file('headerimg')->getClientOriginalName();
$request->file('headerimg')->move('uploads/header',$fileName);
}
$header->title = $request->title;
$header->discription = $request->discription;
$header->keywords = $request->keywords;
$header->headerimg = $fileName;
$header->h2 = $request->h2;
$header->breadcumb = $request->breadcumb;
$header->category = $request->category;
$header->save();
return redirect()->route('dashboard.headers.index')->with('success', 'Page Edited Successfully');
}

Laravel socialite Save avatar

everybody, I need to Save image name in the avatar column in the database
and save the image in public/Storage/users My Code Here Save image link in the database any help, please.
public function handleProviderCallback($service)
{
$user = Socialite::driver($service)->user();
$FindUser = User::where('email',$user->getEmail())->first();
if($FindUser){
Auth::login($FindUser);
}
else{
$NewUser = new User;
$NewUser->email = $user->getEmail();
$NewUser->name = $user->getName();
$NewUser->avatar = $user->getAvatar();
$NewUser->password = bcrypt(123456);
$NewUser->save();
Auth::login($NewUser);
}
return redirect('/');
}
Simply fetch the data using file_get_contents function and process the retrieved data.
use File;
create a helper method to get the avatar
function getSocialAvatar($file, $path){
$fileContents = file_get_contents($file);
return File::put(public_path() . $path . $user->getId() . ".jpg", $fileContents);
}
replace $user->getAvatar()
with the helper method
getSocialAvatar($user->getAvatar(), 'path')

why jpg file are saved as tmp in laravel 5.1

I'm trying to upload image in admin panel. but this image is uploading as tmp.
Need I add something other code in my code?
public function store(Request $request)
{
if ($request->hasFile('contents')) {
$destinationPath = 'pictures/SliderImages';
$files = $request->contents;
$file_name = $files->getClientOriginalName();
$files->move($destinationPath, $file_name);
echo "Complete";
} else {
echo "No File";
}
$inputs = $request->all();
$sliders = Sliders::Create($inputs);
return redirect()->action('SliderController#index');
}
this is my blade:
#foreach($sliders as $slider)
<tr>
<td>{{$slider->id}}</td>
<td>{{$slider->title}}</td>
<td><img src="{{$slider->contents}}"></td>
</tr>
#endforeach
this is result in phpmyadmin
try this
$inputs = $request->all();
$inputs['contents'] = $file_name; // add this line in your code
$sliders = Sliders::Create($inputs);
return redirect()->action('SliderController#index');
The $inputs you pass in to Sliders::Create looks to be the original $request parameters? Which probably doesn't include the adjustments you made to that uploaded file.

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');
}
}

Categories