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');
}
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);
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');
}
My controller code for upload file in laravel 5.4:
if ($request->hasFile('input_img')) {
if($request->file('input_img')->isValid()) {
try {
$file = $request->file('input_img');
$name = rand(11111, 99999) . '.' . $file->getClientOriginalExtension();
$request->file('input_img')->move("fotoupload", $name);
} catch (Illuminate\Filesystem\FileNotFoundException $e) {
}
}
}
Image was successfully uploaded but the code threw an exception :
FileNotFoundException in MimeTypeGuesser.php line 123
The file is there any fault in my code or is it a bug in laravel 5.4, can anyone help me solve the problem ?
My view code:
<form enctype="multipart/form-data" method="post" action="{{url('admin/post/insert')}}">
{{ csrf_field() }}
<div class="form-group">
<label for="imageInput">File input</label>
<input data-preview="#preview" name="input_img" type="file" id="imageInput">
<img class="col-sm-6" id="preview" src="">
<p class="help-block">Example block-level help text here.</p>
</div>
<div class="form-group">
<label for="">submit</label>
<input class="form-control" type="submit">
</div>
</form>
Try this code. This will solve your problem.
public function fileUpload(Request $request) {
$this->validate($request, [
'input_img' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if ($request->hasFile('input_img')) {
$image = $request->file('input_img');
$name = time().'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/images');
$image->move($destinationPath, $name);
$this->save();
return back()->with('success','Image Upload successfully');
}
}
You can use it by easy way, through store method in your controller
like the below
First, we must create a form with file input to let us upload our file.
{{Form::open(['route' => 'user.store', 'files' => true])}}
{{Form::label('user_photo', 'User Photo',['class' => 'control-label'])}}
{{Form::file('user_photo')}}
{{Form::submit('Save', ['class' => 'btn btn-success'])}}
{{Form::close()}}
Here is how we can handle file in our controller.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
public function store(Request $request)
{
// get current time and append the upload file extension to it,
// then put that name to $photoName variable.
$photoName = time().'.'.$request->user_photo->getClientOriginalExtension();
/*
talk the select file and move it public directory and make avatars
folder if doesn't exsit then give it that unique name.
*/
$request->user_photo->move(public_path('avatars'), $photoName);
}
}
That’s it. Now you can save the $photoName to the database as a user_photo field value. You can use asset(‘avatars’) function in your view and access the photos.
A good logic for your application could be something like:
public function uploadGalery(Request $request){
$this->validate($request, [
'file' => 'required|image|mimes:jpeg,png,jpg,bmp,gif,svg|max:2048',
]);
if ($request->hasFile('file')) {
$image = $request->file('file');
$name = time().'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/storage/galeryImages/');
$image->move($destinationPath, $name);
$this->save();
return back()->with('success','Image Upload successfully');
}
}
Use the following code:
$imageName = time().'.'.$request->input_img->getClientOriginalExtension();
$request->input_img->move(public_path('fotoupload'), $imageName);
public function store()
{
$this->validate(request(), [
'title' => 'required',
'slug' => 'required',
'file' => 'required|image|mimes:jpg,jpeg,png,gif'
]);
$fileName = null;
if (request()->hasFile('file')) {
$file = request()->file('file');
$fileName = md5($file->getClientOriginalName() . time()) . "." . $file->getClientOriginalExtension();
$file->move('./uploads/categories/', $fileName);
}
Category::create([
'title' => request()->get('title'),
'slug' => str_slug(request()->get('slug')),
'description' => request()->get('description'),
'category_img' => $fileName,
'category_status' => 'DEACTIVE'
]);
return redirect()->to('/admin/category');
}
Intervention Image is an open source PHP image handling and manipulation library
http://image.intervention.io/
This library provides a lot of useful features:
Basic Examples
// open an image file
$img = Image::make('public/foo.jpg');
// now you are able to resize the instance
$img->resize(320, 240);
// and insert a watermark for example
$img->insert('public/watermark.png');
// finally we save the image as a new file
$img->save('public/bar.jpg');
Method chaining:
$img = Image::make('public/foo.jpg')->resize(320, 240)->insert('public/watermark.png');
Tips: (In your case)
https://laracasts.com/discuss/channels/laravel/file-upload-isvalid-returns-false
Tips 1:
// Tell the validator input file should be an image & check this validation
$rules = array(
'image' => 'mimes:jpeg,jpg,png,gif,svg // allowed type
|required // is required field
|max:2048' // max 2MB
|min:1024 // min 1MB
);
// validator Rules
$validator = Validator::make($request->only('image'), $rules);
// Check validation (fail or pass)
if ($validator->fails())
{
//Error do your staff
} else
{
//Success do your staff
};
Tips 2:
$this->validate($request, [
'input_img' =>
'required
|image
|mimes:jpeg,png,jpg,gif,svg
|max:1024',
]);
Function:
function imageUpload(Request $request) {
if ($request->hasFile('input_img')) { //check the file present or not
$image = $request->file('input_img'); //get the file
$name = "//what every you want concatenate".'.'.$image->getClientOriginalExtension(); //get the file extention
$destinationPath = public_path('/images'); //public path folder dir
$image->move($destinationPath, $name); //mve to destination you mentioned
$image->save(); //
}
}
if ($request->hasFile('input_img')) {
if($request->file('input_img')->isValid()) {
try {
$file = $request->file('input_img');
$name = time() . '.' . $file->getClientOriginalExtension();
$request->file('input_img')->move("fotoupload", $name);
} catch (Illuminate\Filesystem\FileNotFoundException $e) {
}
}
}
or follow
https://laracasts.com/discuss/channels/laravel/image-upload-file-does-not-working
or
https://laracasts.com/series/whats-new-in-laravel-5-3/episodes/12
i think better to do this
if ( $request->hasFile('file')){
if ($request->file('file')->isValid()){
$file = $request->file('file');
$name = $file->getClientOriginalName();
$file->move('images' , $name);
$inputs = $request->all();
$inputs['path'] = $name;
}
}
Post::create($inputs);
actually images is folder that laravel make it automatic and file is name of the input and here we store name of the image in our path column in the table and store image in public/images directory
// get image from upload-image page
public function postUplodeImage(Request $request)
{
$this->validate($request, [
// check validtion for image or file
'uplode_image_file' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048',
]);
// rename image name or file name
$getimageName = time().'.'.$request->uplode_image_file->getClientOriginalExtension();
$request->uplode_image_file->move(public_path('images'), $getimageName);
return back()
->with('success','images Has been You uploaded successfully.')
->with('image',$getimageName);
}
This code will store the image in database.
$('#image').change(function(){
// FileReader function for read the file.
let reader = new FileReader();
var base64;
reader.readAsDataURL(this.files[0]);
//Read File
let filereader = new FileReader();
var selectedFile = this.files[0];
// Onload of file read the file content
filereader.onload = function(fileLoadedEvent) {
base64 = fileLoadedEvent.target.result;
$("#pimage").val(JSON.stringify(base64));
};
filereader.readAsDataURL(selectedFile);
});
HTML content should be like this.
<div class="col-xs-12 col-sm-4 col-md-4 user_frm form-group">
<input id="image" type="file" class="inputMaterial" name="image">
<input type="hidden" id="pimage" name="pimage" value="">
<span class="bar"></span>
</div>
Store image data in database like this:
//property_image longtext(database field type)
$data= array(
'property_image' => trim($request->get('pimage'),'"')
);
Display image:
<img src="{{$result->property_image}}" >
public function ImageUplode(Request $request) {
if ($request->hasFile('image')) {
$file = $request->file('image');
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$picture = $request['code'].'.jpg';
//move image to public/image folder
$file->move(public_path('imgage'), $picture);
// image uplode function Succesfully saved message
return response()->json(["message" => "Image Uploaded Succesfully"]);
}
else {
return response()->json(["message" => "Select image first."]);
}
}
In Laravel 5.4, you can use guessClientExtension
Please find below the coded section,
You can give your inputs based on the interpretation.
public function upload(Request $request)
{
$content = $_POST['code'];
if (Storage::exists('file.blade.php'))
{
echo "File is already exists..............";
}
else
{
Storage::disk('local')->put('file.blade.php', $content);
echo "uploaded successfully...........";
$fileName = "file.blade.php";
$oldPath = "/storage/app/file.blade.php";
$destinationPath = "/resources/views";
File::move($oldPath, $destinationPath);
}
}
I have used the above code trying to move the file. But I got the following error message.
ErrorException in Filesystem.php line 176:
rename(/storage/app/file.blade.php,/resources/views): The system
cannot find the path specified. (code: 3)
Try changing like this:
$fileName = "file.blade.php";
$oldPath = "/storage/app/file.blade.php";
//$destinationPath = "/resources/views"."$fileName";
$destinationPath = "/resources/views/"."$fileName";