Laravel multi image upload - php

I am trying to save multiple images but I get the error show in the image at the bottom of the post.
I have tried doing a request of the name, but I get another error, I have a one to many relationship between property and images, I am trying to save many images of a property.
If I am receiving the image, if I make a dd before the creation I receive the image.
store method
public function store(Request $request)
{
/*--from this session you start to save the properties with all their attributes --*/
$properti = new Propertie;
$detail = new Detail;
$detail->antiquity = $request->antiquity;
$detail->furnished = $request->furnished;
$detail->floor = $request->floor;
$detail->save();
$properti->details_id = $detail->id;
$properti->name = $request->name;
$properti->price = $request->price;
$properti->description = $request->description;
$properti->departaments_id = $request->departaments;
$properti->municipalities_id = $request->municipalities;
$properti->property_type_id = $request->type_property;
$properti->offer_type_id = $request->type;
$properti->details_id = $detail->id;
$properti->lat = $request->lat;
$properti->lng = $request->lng;
$properti->address = $request->address;
if (isset($request->property_id)) {
$property_type = $request->property_id;
} else {
$property_type = null;
}
$properti->save();
$image->name = $request->name;
foreach($request->file('images') as $image ){
$name = $image->getClientOriginalName();
$image->move('image',$name);
}
$properti->images()->create(['name' => $name ]);
$piso_id = $properti->id;
$space = new Space;
$space->property_id = $piso_id;
$space->bedrooms = $request->bedrooms;
$space->bathrooms = $request->bathrooms;
$space->parking = $request->parking;
$space->area = $request->area;
$space->save();
$properti->spaces_id = $space->id;
foreach ($request->input('characteristic') as $characteristic) {
$charc = new Characteristic;
$charc->property_id = $piso_id;
$charc->characteristic = $characteristic;
$charc->save();
}
Session::flash('message', 'Se ha registrado su propiedad De forma exitosa');
return redirect()->action('PropertyController#index',compact('name'));
// return view('properties.index',compact('properties'));
}
File input
<div class="custom-file">
<input required type="file" class="form-control" name="images" placeholder="Imagenes" multiple>
</div>

Looks like this error happens only if there are no images attached. You should attach the image while looping over the request data:
foreach ($request->file('images') as $image) {
$name = $image->getClientOriginalName();
$image->move('image', $name);
// v- TO HERE -v
$properti->images()->create(['name' => $name ]);
}
// MOVE THIS: $properti->images()->create(['name' => $name ]);

as i see, you are calling a variable $name defined inside a foreach loop which mean it's not defined outside the loop, and that's what the error said.

Related

Foreach loop not working properly in my Laravel 9 Code?

Screen Shot of HTML Form.
Can you suggest me where am I doing mistakes in my Laravel app, each time i am uploading multiple files throug the form, files is uploading perfectly in given location, but only 1 records are being inserted into database table. Here is my code...
// Upload bg_certificateArr photo
if ($request->hasFile('bg_certificate')) {
foreach ($request->file('bg_certificate') as $key => $file) {
// Get image extention
$extention = $file->getClientOriginalExtension();
// Generate new image name
$bgCertImgName = 'ac-bg-cert-' . date('Y-m-d-H-i-s') . '.' . $extention;
$bgCertImgPath = 'accountant/images/bank_guarantee/' . $bgCertImgName;
// Upload Profile Image
Image::make($file)->save($bgCertImgPath);
// Insert data into bank guarantee table
$bg_amountArr = $data['bg_amount'];
$bg_numberArr = $data['bg_number'];
$bank_idArr = $data['bank_id'];
$bg_from_dateArr = $data['bg_from_date'];
$bg_to_dateArr = $data['bg_to_date'];
$bg_amount = $bg_amountArr[$key];
$bg_number = $bg_numberArr[$key];
$bank_id = $bank_idArr[$key];
$bg_from_date = $bg_from_dateArr[$key];
$bg_to_date = $bg_to_dateArr[$key];
// echo '<pre>';
// print_r($bg_to_date);
// die();
$ac_bg->school_id = $schoolID;
$ac_bg->ledgers_id = $acLedger->id;
$ac_bg->bg_amount = $bg_amount;
$ac_bg->bg_number = $bg_number;
$ac_bg->bank_id = $bank_id;
$ac_bg->bg_from_date = $bg_from_date;
$ac_bg->bg_to_date = $bg_to_date;
$ac_bg->bg_certificate = $bgCertImgName;
$ac_bg->save();
}
}
initialize $ac_bg for every foreach loop.
if ($request->hasFile('bg_certificate')) {
foreach ($request->file('bg_certificate') as $key => $file) {
$ac_bg = new AccountBankGuarantee; // like this
// Get image extention
$extention = $file->getClientOriginalExtension();
// Generate new image name
$bgCertImgName = 'ac-bg-cert-' . date('Y-m-d-H-i-s') . '.' . $extention;
$bgCertImgPath = 'accountant/images/bank_guarantee/' . $bgCertImgName;
// Upload Profile Image
Image::make($file)->save($bgCertImgPath);
// Insert data into bank guarantee table
$bg_amountArr = $data['bg_amount'];
$bg_numberArr = $data['bg_number'];
$bank_idArr = $data['bank_id'];
$bg_from_dateArr = $data['bg_from_date'];
$bg_to_dateArr = $data['bg_to_date'];
$bg_amount = $bg_amountArr[$key];
$bg_number = $bg_numberArr[$key];
$bank_id = $bank_idArr[$key];
$bg_from_date = $bg_from_dateArr[$key];
$bg_to_date = $bg_to_dateArr[$key];
// echo '<pre>';
// print_r($bg_to_date);
// die();
$ac_bg->school_id = $schoolID;
$ac_bg->ledgers_id = $acLedger->id;
$ac_bg->bg_amount = $bg_amount;
$ac_bg->bg_number = $bg_number;
$ac_bg->bank_id = $bank_id;
$ac_bg->bg_from_date = $bg_from_date;
$ac_bg->bg_to_date = $bg_to_date;
$ac_bg->bg_certificate = $bgCertImgName;
$ac_bg->save();
}
}
You haven't posted full code here, but I believe before loop you somehow set $ac_bg variable. So looking at your code you create one record and update it in every next loop iteration.
So to fix this you should probably do something like this:
foreach ($request->file('bg_certificate') as $key => $file) {
$ac = new Ac(); // don't know what's the exact model class here
Then in every loop iteration you will create new record instead of updating it.

Shorter way in php laravel to load a model in another similar one?

I want to copy every property of the contract model into this another templatecontract model and so on. My code works, but I don't know much about laravel (or php in fact) and my intuition tells me that there must be a better way, or more elegant way.
fill() from Laravel does not get much better. Maybe with a constructor?
Equal tables:
Contract -> TemplateContract
Chapter -> TemplateChapter
Clause -> TemplateClause
public function storeTemplate(ContractCreateRequest $request)
{
DB::beginTransaction();
try
{
$contract = Contract::find($request->input()['type']);
$templatecontract = new TemplateContract();
$templatecontract->id = $contract->id;
$templatecontract->pid = $contract->pid;
$templatecontract->deleted = $contract->deleted;
$templatecontract->sorting = $contract->sorting;
$templatecontract->created_at = $contract->created_at;
$templatecontract->updated_at = $contract->updated_at;
$templatecontract->deleted_at = $contract->deleted_at;
$templatecontract->title = $contract->title;
$templatecontract->description = $contract->description;
$templatecontract->hidden = $contract->hidden;
$templatecontract->contract_type = $contract->contract_type;
$templatecontract->process_type = $contract->process_type;
$templatecontract->tstamp = $contract->tstamp;
$templatecontract->is_english = $contract->is_english;
$templatecontract->usecasetitle = $contract->usecasetitle;
if (Auth::user()) {
$templatecontract->user_id = Auth::user()->id;
}
if($templatecontract->save())
{
$chapter = DB::table('chapter')->where('contract', $templatecontract->id)->get();
if(isset($chapter))
{
foreach ($chapter as $key => $value) {
$templatechapter = new TemplateChapter();
$templatechapter->clause = $value->clause;
$templatechapter->contract = $value->contract;
$templatechapter->created_at = $value->created_at;
$templatechapter->deleted = $value->deleted;
$templatechapter->headlinetype = $value->headlinetype;
$templatechapter->hidden = $value->hidden;
$templatechapter->id = $value->id;
$templatechapter->must = $value->must;
$templatechapter->note = $value->note;
$templatechapter->sorting = $value->sorting;
$templatechapter->title = $value->title;
$templatechapter->tstamp = $value->tstamp;
$templatechapter->updated_at = $value->updated_at;
$templatechapters[] = $templatechapter;
if($templatechapter->save())
{
$clause = DB::table('clause')->where('chapter', $value->id)->get();
if(isset($clause))
{
foreach ($clause as $key => $value) {
$templateclause = new TemplateClause();
$templateclause->id = $value->id;
$templateclause->chapter = $value->chapter;
$templateclause->clausetext = $value->clausetext;
$templateclause->variable = $value->variable;
$templateclause->topic = $value->topic;
$templateclause->deleted = $value->deleted;
$templateclause->selectword = $value->selectword;
$templateclause->shortinfo = $value->shortinfo;
$templateclause->sorting = $value->sorting;
$templateclause->created_at = $value->created_at;
$templateclause->updated_at = $value->updated_at;
$templateclause->hidden = $value->hidden;
$templateclause->tstamp = $value->tstamp;
$templateclause->save();
$templateclauses[] = $templateclause;
}
}
}
}
}
}
//DB::commit();
return response()->success(__('success.showing', ['resource' => 'des Vertrags', 'resourceE' => 'contract']), $templatecontract, 200);
}
catch (Exception $e)
{
return response()->error(__('error.showing', ['resource' => 'des Vertrags', 'resourceE' => 'contract']), 400, $e);
}
}
So almost all of the props from the request matches with the column names. You just need to call the create method of Eloquent model to create a new record and pass key value pair but rather an object. Also, you need not to worry about the extra parameters $contract contains since Laravel will only extract and assign params defined in protected $fillable property of the class.
// cast object to array
$contract = (array) $contract;
$templateContract = TemplateContract::create($contract)

Use inserted ids from Laravel and Dropzone image uploaded data

I have a form with a Dropzone div, for massive image uploads with another data.
But, as the images are uploaded with ajax I need to know which Id's are assigned to those images.
The problem became when I save those ids in the session data. It just saves the first and the latest ids.
For example, when I submit 4 images it returns me the second and the last id.
😒
My controller method (via Ajax):
public function store(Request $request)
{
$photos = $request->file('file');
if (!is_array($photos))
$photos = [$photos];
if (!is_dir($this->photos_path))
mkdir($this->photos_path, 0777);
for ($i = 0; $i < count($photos); $i++) {
$photo = $photos[$i];
$name = sha1(date('YmdHis') . str_random(30));
$save_name = $name . '.' . $photo->getClientOriginalExtension();
$resize_name = $name . str_random(2) . '.' . $photo->getClientOriginalExtension();
Image::make($photo)
->resize(250, null, function ($constraints) {
$constraints->aspectRatio();
})
->save($this->photos_path . '/' . $resize_name);
$photo->move($this->photos_path, $save_name);
$upload = new UploadedImages();
$upload->filename = $save_name;
$upload->resized_name = $resize_name;
$upload->original_name = basename($photo->getClientOriginalName());
$upload->user_id = Auth::id();
$upload->save();
Session::push('uploaded_images_ids', $upload->id);
}
return Response::json(['message' => 'Image saved Successfully'], 200);
}
Response with Debug bar (should response 4 ids, not 2):
You can create an array to store your image and id
Here is the idea below
$image_array = [];
for ($i = 0; $i < count($photos); $i++) {
....
array_push($image_array,['image_name' => $save_name, 'image_id' => $upload->id]);
}

PHP CodeIgniter - How to count images inside folders and their respective subfolders

How to count total numbers of images inside our folders and subfolders?
I put this in my view. Well, as MVC way, this may look sucks to be in view. I know how to put this into models, but don't know how to call it with controllers and views
<?php
$img = count(glob("./assets/images/*.*"));
$about = count(glob("./assets/images/aboutus/*.*"));
$blog1 = count(glob("./assets/images/blog/*.*"));
$mason = count(glob("./assets/images/blog/masonary/*.*"));
$tl = count(glob("./assets/images/blog/timeline/*.*"));
$blog2 = count(glob("./assets/images/blogdetails/*.*"));
$gallery = count(glob("./assets/images/gallery/*.*"));
$home = count(glob("./assets/images/home/*.*"));
$home2 = count(glob("./assets/images/home/slider/*.*"));
$ico = count(glob("./assets/images/ico/*.*"));
$lb = count(glob("./assets/images/lightbox/*.*"));
$keg = count(glob("./assets/images/kegiatan/*.*"));
$port1 = count(glob("./assets/images/portfolio/*.*"));
$port2 = count(glob("./assets/images/portfolio-details/*.*"));
$leader = count(glob("./assets/images/leaders/*.*"));
$srv = count(glob("./assets/images/services/*.*"));
$usr = count(glob("./assets/images/users/*.*"));
$count = $img+$about+$blog1+$mason+$tl+$blog2+$gallery+$home+$home2+$ico+$lb+$keg+$port1+$port2+$leader+$srv+$usr;
?>
Output:
<div class="col-sm-3 text-center wow bounceIn" data-wow-duration="1000ms" data-wow-delay="300ms">
<h1 class="timer bold" data-to="<?= $count;?>" data-speed="3000" data-from="0"></h1>
<h3>Total Images</h3>
</div>
Is there a way to make this simple?
Please take a look at
https://stackoverflow.com/a/10895775/7089527
You could do it like this using the [RecursiveDirectoryIterator][1]
<?php
function scan_dir($path){
$ite=new RecursiveDirectoryIterator($path);
$bytestotal=0;
$nbfiles=0;
foreach (new RecursiveIteratorIterator($ite) as $filename=>$cur) {
$filesize=$cur->getSize();
$bytestotal+=$filesize;
$nbfiles++;
$files[] = $filename;
}
$bytestotal=number_format($bytestotal);
return array('total_files'=>$nbfiles,
'total_size'=>$bytestotal,'files'=>$files);
}
$files = scan_dir('./');
echo "Total: {$files['total_files']} files, {$files['total_size']} >bytes\n";
//Total: 1195 files, 357,374,878 bytes
?>
[1]: http://php.net/manual/en/class.recursivedirectoryiterator.php
Hope it helps
Format to call a method in a model from a controller.
Model file:
application/models/Photo_shoot_model.php
class Photo_shoot_model extends CI_Model {
public function image_count() {
$img = count(glob("./assets/images/*.*"));
$about = count(glob("./assets/images/aboutus/*.*"));
$blog1 = count(glob("./assets/images/blog/*.*"));
$mason = count(glob("./assets/images/blog/masonary/*.*"));
$tl = count(glob("./assets/images/blog/timeline/*.*"));
$blog2 = count(glob("./assets/images/blogdetails/*.*"));
$gallery = count(glob("./assets/images/gallery/*.*"));
$home = count(glob("./assets/images/home/*.*"));
$home2 = count(glob("./assets/images/home/slider/*.*"));
$ico = count(glob("./assets/images/ico/*.*"));
$lb = count(glob("./assets/images/lightbox/*.*"));
$keg = count(glob("./assets/images/kegiatan/*.*"));
$port1 = count(glob("./assets/images/portfolio/*.*"));
$port2 = count(glob("./assets/images/portfolio-details/*.*"));
$leader = count(glob("./assets/images/leaders/*.*"));
$srv = count(glob("./assets/images/services/*.*"));
$usr = count(glob("./assets/images/users/*.*"));
$count = $img+$about+$blog1+$mason+$tl+$blog2+$gallery+$home+$home2+$ico+$lb+$keg+$port1+$port2+$leader+$srv+$usr;
return $count;
}
}
In controller:
public function index() {
// load model
$this->load->model('photo_shoot_model');
// call method
$howManyImages = $this->photo_shoot_model->image_count()
}
All about models: https://codeigniter.com/user_guide/general/models.html
But really, I'd use the RecursiveDirectoryIterator mentioned by #MayurVirkar.

Laravel : How to upload Multiple image file in multiple database field?

I want to upload multiple image files in database ..
Here is the view part :
<input type="file" name="photo[]" >
<input type="file" name="photo[]" >
<input type="file" name="photo[]" >
And I want to store the path into different field in database..
controller code:
public function store(Request $request)
{
$product = new Product();
$product->name = $request->Input(['name']);
$product->description = $request->Input(['description']);
$files = Input::file('photo');
$names = [];
foreach ($files as $file) {
$names[] = $file->getClientOriginalExtension();
}
$imageName1 = time().'.'.$names[0];
$imageName2 = time().'.'.$names[1];
$imageName3 = time().'.'.$names[2];
$product->primary_image = $imageName1;
$file->move('images/', $imageName1);
$product->optional_image_one = $imageName2;
$file->move('images/', $imageName2);
$product->optional_image_two = $imageName3;
$file->move('images/', $imageName3);
$product->price = $request->Input(['price']);
$product->save();
return Redirect::to('product');
}
I got the following Error:
FileException in UploadedFile.php line 235:
The file "3.jpg" was not uploaded due to an unknown error.
Can anyone what's the error for assigning into object? or solution please ..

Categories