I have multiple image uploader and i want only the first image to get true value and other false. I mean I have DB field name 'isPrimary' , so when I upload multiple images I want only first image get true value and other images get false value.
<div class="col-lg-12 p-t-20">
<label class="control-label col-md-3">Upload Room Photos</label>
<input type = "file" id = "image" name="image[]" multiple class="file" data-overwrite-initial="false"
data-min-file-count="1">
</div>
This is my controller for image store
if($request->hasfile('image')) {
$image = $request->image;
if(count($image) === 1){
$isPrime = $dataa['isPrimary'] = true;
}else{
///So here i need logic to make ('isPrimary') field to be true in only first image when there is multiple images is uploaded
}
foreach ($image as $photo) {
// dd($photo);
$name = $photo->getClientOriginalName();
$filename = $photo->move(('storage/images/room_types/'), $name);
//
$dataa = [
'room_type_id' => $room_type->id,
'image' => $filename,
'isPrimary'=>$isPrime,
];
Image::create($dataa);
}
}
Sorry For my English, I am not good at cause it's my second language .
Thanks, in advance.
Try this
foreach ($image as $photo) {
$name = $photo->getClientOriginalName();
$filename = $photo->move(('storage/images/room_types/'), $name);
$dataa = [
'room_type_id' => $room_type->id,
'image' => $filename,
'isPrimary'=> (\Arr::first($image) == $photo) ? true : false,
];
Image::create($dataa);
}
$is_prime = true;
foreach ($image as $photo) {
$name = $photo->getClientOriginalName();
$filename = $photo->move(('storage/images/room_types/'), $name);
$dataa = [
'room_type_id' => $room_type->id,
'image' => $filename,
'isPrimary'=>$isPrime,
];
$is_prime = false;
}
Image::create($dataa);
Related
When I update the database, it uploads a single image. How do I upload multiple?
$id = $this->request->getPost('id');
$model = new UrunModel();
$file = $this->request->getFile('resim');
$resim_eski = $model->find($id);
if($file->isValid() && !$file->hasMoved()){
$eski_resim = $resim_eski['resim'];
if(file_exists("dosyalar/uploads".$eski_resim)){
unlink("dosyalar/uploads".$eski_resim);
}
$imagename = $file->getRandomName();
$file->move("dosyalar/uploads", $imagename);
}else{
$imagename = $resim_eski['resim'];
}
if ($this->request->getFileMultiple('images')) {
foreach($this->request->getFileMultiple('images') as $res)
{
$res->move(WRITEPATH . 'dosyalar/uploads');
$data=[
'baslik' => $this->request->getPost('baslik'),
'slug' => mb_url_title($this->request->getPost('baslik'), '-', TRUE),
'kisa_aciklama' => $this->request->getPost('kisa_aciklama'),
'kategori' => $this->request->getPost('kategori'),
'query_kategori' => $this->request->getPost('query_kategori'),
'aciklama' => $this->request->getPost('aciklama'),
'fiyat' => $this->request->getPost('fiyat'),
'indirimli_fiyat' => $this->request->getPost('indirimli_fiyat'),
'resim' => $imagename,
'resimler' => $res->getClientName(),
'type' => $res->getClientMimeType()
];
$model -> update($id,$data);
}
}
return redirect()->to(base_url('yonetim/urunler'));
}
Controller code above, I've been struggling for 2 days, I couldn't manage it somehow.
When I run the code, it just adds 1 image to each product. I want to add more than one image to 1 product for the gallery part. Any suggestions for this code or a different solution?
function add()
{
$length = count($_FILES['image']['name']);
$filename = $_FILES['image']['name'];
$tempname = $_FILES['image']['tmp_name'];
$allimage = array();
foreach($filename as $key =>$value)
{
move_uploaded_file($tempname[$key],'media/uploads/mobile_product/'.$filename[$key]);
$allimage[] = $filename[$key];
}
if(!empty($allimage))
{
$allimage = json_encode($allimage);
}
else
{
$allimage = '';
}
$data['image'] = $allimage;
$this->db->insert('table',$data);
}
CI4 Controller:
if($this->request->getFileMultiple('image_files')) {
$files = $this->request->getFileMultiple('image_files');
foreach ($files as $file) {
if ($file->isValid() && ! $file->hasMoved())
{
$newNames = $file->getRandomName();
$imageFiles = array(
'filename' => $newNames
);
$modelName->insert($imageFiles );
$file->move('uploads/', $newNames);
}
}
}
HTML
<input type="file" name="image_files[]">
This is the shortest way to do that
In my property section I have two property types:
Freemium
Premium
I want to restrict users to upload only 5 images for Freemium property type while for Premium properties a user can upload infinitive number images and videos.
Must needed some suggestions.
Here is my image upload part :
public function postProperty(PropertyRequest $request)
{
$user = User::where('id', $request->user->user_id)->first();
if(!empty($user))
{
$data['user_id'] = $user->id;
$data['type'] = $request->type;
$data['category'] = $request->category;
$data['area'] = $request->area;
$data['price'] = $request->price;
$data['description'] = $request->description;
//dd($data);
$property = Property::create($data);
//$property['flag'] = false; // if (flag = false, property = freemium) else (flag = true, property = premium ))
$urls = new PropertyImage();
if ($request->hasFile('url'))
{
$files = $request->file('url');
foreach($files as $file)
{
$mime = $file->getMimeType();
//$property['flag'] = $property->account == 1 ? false : true;
if($mime == 'image/jpeg')
{
$fileName = $file->getClientOriginalName();
$destinationPath = public_path() . '/images/';
$file->move($destinationPath, $fileName);
$urls->url = '/public/images/' . $fileName;
$url_data = [
'property_id' => $property->id,
'url_type' => 1,
'url' => $urls->url,
];
$urls->create($url_data);
}
elseif($mime == 'video/mp4')
{
$fileName = $file->getClientOriginalName();
$destinationPath = public_path() . '/videos/';
$file->move($destinationPath, $fileName);
$urls->url = '/public/videos/' . $fileName;
$url_data = [
'property_id' => $property->id,
'url_type' => 2,
'url' => $urls->url,
];
$urls->create($url_data);
}
}
}
return Utility::renderJson(trans('api.success'), true, $property, $urls );
}
}
You can use laravel validation to restrict user to some number of files as shown below
//If user is Freemium then restrict him
if (!$property['flag']) {
$messages = [
"url.max" => "files can't be more than 3."
];
$this->validate($request, [
'url' => 'max:3',
],$messages);
}
I want to upload and display image, but i get error
Undefined variable: image_name
This is my controller
$supply = new DataSupplyProcess;
if($request->hasFile('supply_photo')){
$photo = Validator::make($request->all(), [
'supply_photo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if($photo->fails()){
return redirect()->back()->with('warning', 'Image size should be 2MB or less');
}
$image = $request->file('supply_photo');
$image_name = rand().'.'. $image->getClientOriginalExtension();
$destination_path = public_path('/item');
$image->move($destination_path, $image_name);
//dd($image);
}
$supply->item = $request->item;
$supply->supply_details = $request->supply_details;
$supply->tgl_request_date = $request->tgl_need_date;
$supply->tgl_need_date = $request->tgl_need_date;
$supply->employee_id = $id;
$supply->id_approved_by = $manager->employee_manager_id;
$supply->is_approved = 0;
$supply->is_final_approved = 0;
$supply->supply_photo = $image_name;
$supply->save();
This Is My View
<label for="supply_photo">Photo</label>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" class="form-control" name="supply_photo">
In your controller, try something like:
if(Input::file('supply_photo') !== null){
$photo = Validator::make($request->all(), [
'supply_photo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
...
}
I think this post can provide more info
when ever you pass variable like this with IF condition assign default value first.
so you won't get error if image not selected.
and in your cause check first you get image or not
dd($image = $request->file('supply_photo'));
$image_name = NULL;
if($request->hasFile('supply_photo')){
$image = $request->file('supply_photo');
$image_name = rand().'.'. $image->getClientOriginalExtension();
$destination_path = public_path('/item');
$image->move($destination_path, $image_name);
}
$supply->supply_photo = $image_name;
$supply->save();
$supply = new DataSupplyProcess;
if($request->hasFile('supply_photo')){
$photo = Validator::make($request->all(), [
'supply_photo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if($photo->fails()){
return redirect()->back()->with('warning', 'Image size should be 2MB or less');
}
//$original_name=$request->file('supply_photo')->getClientOriginalName();
//$size=$request->file('supply_photo')->getSize();
$extension=$request->file('supply_photo')->getClientOriginalExtension();
$filename=uniqid().'.'.$extension;
$imagepath=url('/item/'.$filename);
$path=$request->file('supply_photo')->storeAs(public_path('/item'),$filename);
}
In laravel I have a field in my edit view named Profile Picture, whenever I click On edit button I got all the values from database in edit view but I don't get image, And If whenever I click on submit button everytime I have to upload image without that I can't process further I want If I not upload new image then form will automatic consider old profile pic
my blade file is like
<div class="col-md-6">
<div class="form-group">
<label for="photo">Profile Picture :<span class="danger">*</span> </label>
<div class="row">
<div class="col-md-9">
<input type="file" class="form-control" id="file" name="file">
</div>
<div class="col-md-3">
#foreach ($empProfilePic as $empProfilePicture)
#if($employee->id == $empProfilePicture->id)
<img src="uploads/images/{{ $empProfilePicture->file }}" id="profile-img-tag" height="100" width="100">
#endif
#endforeach
</div>
</div>
</div>
</div>
Controller File
public function updateEmployee(Request $request, $id)
{
$employee = User::find($id);
//Get inputs for personal detail
$firstName = $request->get('firstName');
$middleName = $request->get('middleName');
$lastName = $request->get('lastName');
$gender = $request->get('gender');
$city = $request->get('city');
$state = $request->get('state');
$localAddress = $request->get('localAddress');
$permanentAddress = $request->get('permanentAddress');
$personalEmail = $request->get('personalEmail');
$mobileNumber = $request->get('mobileNumber');
$companyEmail = $request->get('companyEmail');
$empId = $request->get('empId');
$department = $request->get('department');
$designation = $request->get('designation');
$status = $request->get('status');
$totalExperience = $request->get('totalExperience');
$aboutMe = $request->get('aboutMe');
$roleName = $request->get('role');
$role = $request->get('role');
if ($role == 'hr')
{
$role = '5c8a51ed650fbd5398503043';
}
else
{
$role = '5c8a51ed650fbd5398503044';
}
// //Store Image In Folder
$file = $request->file('file');
$name = $file->getClientOriginalName();
$file->move('uploads/images', $name);
if (file_exists(public_path($name = $file->getClientOriginalName())))
{
unlink(public_path($name));
};
$accountHolderName = $request->get('accountHolderName');
$accountNumber = $request->get('accountNumber');
$bankName = $request->get('bankName');
$ifscCode = $request->get('ifsc_code');
$panNumber = $request->get('panNumber');
$branchName = $request->get('branchName');
//Enter in database
$employee->role_id = $role;
$employee->role_name = $roleName;
$employee->username = $firstName;
//Update Image
$employee->file = $name;
$employee->personal_email = $personalEmail;
$employee->company_email = $companyEmail;
$employee->status = $status;
$personalDetail = ([
'emp_id' => $empId,
'first_name' => $firstName,
'middle_name' => $middleName,
'last_name' => $lastName,
'gender' => $gender,
'city' => $city,
'state' => $state,
'local_address' => $localAddress,
'permanent_address' => $permanentAddress,
'personal_email' => $personalEmail,
'mobile_number' => $mobileNumber,
'department' => $department,
'designation' => $designation,
'total_experience' => $totalExperience,
'about_me' => $aboutMe,
]);
$bankDetail = ([
'account_holder_name' => $accountHolderName,
'account_number' => $accountNumber,
'bank_name' => $bankName,
'ifsc_code' => $ifscCode,
'pan_number' => $panNumber,
'branch_name' => $branchName,
]);
$employee->status = $status;
$employee->personal_detail = $personalDetail;
$employee->bank_detail = $bankDetail;
$employee->save();
return redirect('list-of-employees')->with('Success', 'Data Updated Successfully!');
}
Will anyone will help, Thank you in advance
In controller:
Code for update file:
Its update only when you select a file for the update.
Here I use the Employee model you can replace with your model
public function update(Request $request, $id){
$employee = Employee::find($id);
if($request->file != ''){
$path = public_path().'/uploads/images/';
//code for remove old file
if($employee->file != '' && $employee->file != null){
$file_old = $path.$employee->file;
unlink($file_old);
}
//upload new file
$file = $request->file;
$filename = $file->getClientOriginalName();
$file->move($path, $filename);
//for update in table
$employee->update(['file' => $filename]);
}
}
Try this. If you get the file in post method, only then set the file variable of an employee.
// //Store Image In Folder
if (isset($_FILES['file'])) {
$file = $request->file('file');
$name = $file->getClientOriginalName();
$file->move('uploads/images', $name);
if (file_exists(public_path($name = $file->getClientOriginalName())))
{
unlink(public_path($name));
};
//Update Image
$employee->file = $name;
}
//Enter in database
$employee->role_id = $role;
$employee->role_name = $roleName;
$employee->username = $firstName;
Make the image input optional (don't add required) on the blade file and on the validation (controller) then check before updating as:
if ($request->hasFile('image')) {
// Perform image update
}
So I managed to upload multiple images but now I need to display it in a page I tried something like the code below but it says "unidentified variable: photo"
<img class="img-responsive" src="/images/{{ $photo->fileName }}" >
Here's my upload code, updated my code.
Route::post('space/add', array('before' => 'auth', function()
{
$data = Input::all();
$provider_id = Auth::user()->id;
$spaces = Space::where('provider_id', '=', $provider_id)->get();
$space = new Space;
....
$space->save();
$file = Input::file('image');
$provider_email = Auth::user()->email;
// $space = Space::find($id);
$rules = array(
'file' => 'required|mimes:png,gif,jpeg'
);
$validator = \Validator::make(array('file'=> $file), $rules);
if($validator->passes())
{
foreach(Input::file('image') as $file)
{
$ext = $file->guessClientExtension(); // (Based on mime type)
$name = $file->getClientOriginalName();
$fileName = md5($name) . '.' .$ext;
$destinationPath = 'images/' . $provider_email;
$file = $file->move($destinationPath, $fileName);
$photo = new Image;
$photo->provider_id = $provider_id;
$photo->spaces_id = $space->id;
$photo->filename = $fileName;
$photo->path = $destinationPath;
$photo->save();
}
} else{
//Does not pass validation
$errors = $validator->errors();
}
return Redirect::to('user/spaces')->with(array('spaces' => $spaces, 'photo' => $photo));
}));
you need to do something like
return View::make('yourviewname')->with('photo', $photo);
this will be in your route or your controller depending on your setup
EDIT:
You will access your varaible in user/spaces through $photo = Session::get('photo') from user/spaces you will pass that variable in your with i.e. ->with('photo', $photo)