Data in loop is repeated - laravel-5

I am trying to work something out. I have the following
$fileString = "";
if (Input::hasFile('filePath')) {
$files = Input::file('filePath');
dd($files);
foreach($files as $file) {
$file->move(public_path('uploads'), $file->getClientOriginalName());
$fileString .= public_path('uploads') . '/' . $file->getClientOriginalName();
$uploadDoc = new ReportingDocUpload();
$uploadDoc->filename = $file->getClientOriginalName();
$uploadDoc->mime = $file->getClientOriginalExtension();
$uploadDoc->filepath = $fileString;
$uploadDoc->documentId = $dsReportingDoc->id;
$uploadDoc->save();
}
}
For each uploaded file, it should create a new row in the database. The dd I have displays something like the following if I upload 3 documents
array:3 [▼
0 => UploadedFile {#29 ▶}
1 => UploadedFile {#30 ▶}
2 => UploadedFile {#31 ▶}
]
So this all looks good. So, I have a loop which should loop each UploadedFile and save it to the database.
At the moment, this kind of works. A new row is added for each uploaded document, and everything besides one thing looks correct.
The thing that is wrong is the filePath. For the first row, this is fine. The second row in the database contains the filePath for both the first file and the second file. And the third row shows the filePath for all three rows. This should only contain the filePath for the current file.
I have looked over it, and not sure what I am missing, but for some reason this is occuring.
Am I missing something obvious here?
Thanks

Because you are setting the $fileString="" outside the loop, every time it goes in the loop, it concatenates to the exists.
Example
$fileString = ""
Loop 1:
$fileString .= a
Loop 2:
$fileString .= b
$fileString = ab
If you clear the the value in each loop, the result is what you need,
Example:
Loop 1:
$fileString = ""
$fileString = a
Loop 2:
$fileString = ""
$fileString = b
If you use the = instead of the .=, you might not need to assign it to an empty string inside the loop

Move $fileString = ""; inside the foreach loop or change $fileString .= public_path('uploads') . '/' . $file->getClientOriginalName(); to $fileString = public_path('uploads') . '/' . $file->getClientOriginalName();

Related

Codeigniter update_batch in Core PHP

everyone.
In the codeigniter there is update_batch function by using it we are able to bulk update multiple rows.
$this->db->update_batch('table_name', $update_data_array, 'where_condition_field_name');
I want similar functionality in core PHP in one function or in one file. Is there any workaround?
Is there any way to extract update_batch function from Codeigniter in one file/function?
I tried to extract this function but it is very lengthy process and there will be many files / functions should be extracted.
Please help me in this regard
Thanks in advance
You can also insert multiple rows into a database table with a single insert query in core php.
(1)One Way
<?php
$mysqli = new mysqli("localhost", "root", "", "newdb");
if ($mysqli == = false) {
die("ERROR: Could not connect. ".$mysqli->connect_error);
}
$sql = "INSERT INTO mytable (first_name, last_name, age)
VALUES('raj', 'sharma', '15'),
('kapil', 'verma', '42'),
('monty', 'singh', '29'),
('arjun', 'patel', '32') ";
if ($mysqli->query($sql) == = true)
{
echo "Records inserted successfully.";
}
else
{
echo "ERROR: Could not able to execute $sql. "
.$mysqli->error;
}
$mysqli->close();
? >
(2)Second Way
Let's assume $column1 and $column2 are arrays with same size posted by html form.
You can create your sql query like this:-
<?php
$query = 'INSERT INTO TABLE (`column1`, `column2`) VALUES ';
$query_parts = array();
for($x=0; $x<count($column1); $x++){
$query_parts[] = "('" . $column1[$x] . "', '" . $column2[$x] . "')";
}
echo $query .= implode(',', $query_parts);
?>
You can easily construct similar type of query using PHP.
Lets use array containing key value pair and implode statement to generate query.
Here’s the snippet.
<?php
$coupons = array(
1 => 'val1',
2 => 'va2',
3 => 'val3',
);
$data = array();
foreach ($coupons AS $key => $value) {
$data[] = "($key, '$value')";
}
$query = "INSERT INTO `tbl_update` (id, val) VALUES " . implode(', ', $data) . " ON DUPLICATE KEY UPDATE val = VALUES(val)";
$this->db->query($query);
?>
Alternatively, you can use CASE construct in UPDATE statement. Then the query would be something
like:
UPDATE tbl_coupons
SET code = (CASE id WHEN 1 THEN 'ABCDE'
WHEN 2 THEN 'GHIJK'
WHEN 3 THEN 'EFGHI'
END)
WHERE id IN(1, 2 ,3);

images are saving like tmp file in public folder

hi m trying to add data in db but images saves like tmp file, m storing these pics in ecommmerce\public\images\backend_images\category_images and these real pics are not saving instead their real name in db they are saving in folder like this: https://ibb.co/CHXTm3j .. any solution . here is my code:
store function:
$category = new Category;
$category->category_name = $request->category_name;
$category->category_description = $request->category_description;
$category->category_slug = $request->category_slug;
$path = $request->file('category_image');
$image = $path->getClientOriginalName();
$path->move(public_path('images/backend_images/category_images'));
$category->category_image = $image;
$category->save();
Since you are missing the parameter for filename there. Your function to move the original file should be:
$path->move(public_path('images/backend_images/category_images'), $image);
If you do not provide that parameter, the default value would be temp name of the file rather than it's original name.

Count number of same values in JSON array and convert it to string

My JSON looks something like this:
[
{"pet_type":"Dog","weight":"26","description":"Akita"},
{"pet_type":"Dog","weight":"6","description":"Pug"},
{"pet_type":"Cat","weight":"4","description":"Manx"},
{"pet_type":"Dog","weight":"12","description":"Beagle"},
{"pet_type":"Cat","weight":"5","description":"Siberian"}
]
How could I convert it to a string which would look like3 Dogs, 2 Cats?
The way I tried is filling an array with pet_type and than use array_count_values to count number of same records, and later I go through that array in a foreach and concat string like this:
foreach ($count_animals as $type => $number) {
$animals .= $number.' '.str_plural($type, $number).', ';
}
This works, but my question is, could I do it with less code, directly from JSON, without using one more foreach loop?
If it works, you can keep your code.
If you want less code, you can use this version :
$json = '[
{"pet_type":"Dog","weight":"26","description":"Akita"},
{"pet_type":"Dog","weight":"6","description":"Pug"},
{"pet_type":"Cat","weight":"4","description":"Manx"},
{"pet_type":"Dog","weight":"12","description":"Beagle"},
{"pet_type":"Cat","weight":"5","description":"Siberian"}
]';
print_r(array_count_values(array_map(function($item) {
return $item['pet_type'];
}, json_decode($json, true))));
Gonna display :
Array ( [Dog] => 3 [Cat] => 2 )
in your controller
$pet = Pet::get();
$petcount = Pet::where('pet_type','Dog')->get();
In your blade
<h1>{{count($petcount)}} Dog</h1>

Pasting serial numbers to existing entries from a forloop in laravel

I am trying to batch input a number of items, once they are in the database I want to add a unique suffix to the end of the item name. As an example:
[1]Item becomes Item-0001
[2]Item becomes Item-0002 etc....
I have this code at the moment:
$initial = Batches::orderBy('created_at', 'desc')->first();
$batch = Inventory::where('production_id', '=', $initial['batch'])->get();
$production_code = $initial['batch'];
for ($i=0; $i<($data['quantity']); $i++){
$index[]=$i;
}
$batch->each(function ($item, $index) use ($production_code) {
$item->update(['item' => $production_code . '-'.$index]);
});
This works and labels each of the items however it will only add it like so:
Item-0
Item-1
etc..
I would like to find a way to specify the suffix that is added and the starting number, in this case 0001.
Any help would be appreciated.
Thanks
Just add some leading Zeros:
sprintf('%04d', 1); // = 0001
sprintf('%04d', 113); // = 0113
Try to use sprintf() function:
sprintf("%'04d", $index);

Symfony findOneBy / findBy

Has anyone face this strange issue with Symfony 3 (very last version)?
I have the following simple code:
$repository = $this->getDoctrine()
->getManager()
->getRepository('GeneralRegistrationBundle:Service');
$service = $repository->findOneBy(array('name' => 'Registration'),array('name' => 'ASC'));
$comment = $service->getComment();
$name = $service->getName();
return new Response('le service is '. $name . ', content is ' . $comment);
this code works.
I purge the cache and change findOneBy with findBy:
$service = $repository->findBy(array('name' => 'Registration'),array('name' => 'ASC'),1 ,0);
then I have the following error:
Error: Call to a member function getComment() on array
Is anybody have ideas or clues?
Thanks in advance.
findBy() returns an array of objects with the given conditions.
It returns an empty array if none is found. If there is only one row satisfying your condition then you can add a [0] at the last of your $service like this:
$service = $repository->findBy(array('name' => 'Registration'),array('name' => 'ASC'),1 ,0)[0];
if not, you should loop through the found array with foreach or some thing similar.
If you want and expect one result you can use findOneBy() function.
$service = $repository->findOneBy(array('name' => 'Registration'),array('name' => 'ASC'),1 ,0)[0];

Resources