Laravel print object into html table - laravel

I have this kind structured object
{
- NewYorkCity: [
-{
Men:100
},
-{
Women: 100
},
],
- Boston: [
-{
Men:120
},
-{
Women: 180
}
I just want to print those inline, like this:
NewyorkCity | 100 | 100
Boston | 120 | 180
I tried this code:
#foreach($cities as $key => $val)
<tr>
<td> {{$key}}</td>
<td>{{$val[1]}}</td>
</tr>
#endforeach
In this situation, $key (city names ) prints without problem.
men and women counts not. it gives error "Array to string conversion "
How can i fix it?
Thanks.

If you would want your array to be indexable you should change your data accordingly e.g.
array(
NewYorkCity => array(
100,
100
)
);
Than you could use $val[0] and $val[1] in your blade foreach loop, but i would not do this, since than there is no clarification what these values stand for. If you would have to provide more data in the future it gets even more messy, so just use $val["Men"] or $val["Women"].

Try $val['Men'] and $val['Women']

Related

Get null if not found in the database Laravel

I have a problem with Eloquent, my query is:
$b = Dictionary::find($a,$LangtoTranslate);
The problem is count($a) is 67, count($b) is 64..can I get null if value is not founded? In my case, the missing row in $a are "" but I need to have null or "" if not I lost syncronism.
The $a is a simple array:
array:67 [▼
0 => ""
1 => "Frase fatale non identificato"
2 => "Indice fuori dei limiti"
3 => "Errata configurazione del componente"
4 => "Raggiunto il numero massimo di annidamenti"
5 => "Id sequenza non identificata"
6 => "Rassegnazione"
7 => "Salto ad uno step coesistente"
8 => "RETURN senza passare dal via"
9 => "Da Implementare"
The DB is made just from language columns:
it- IT
en-GB
de-DE
Other Languages
Italiano
English
Deutsch
i've tried olso:
$b = Dictionary::where($reflang,$a)->first($LangtoTranslate);
But I get null
For reference:
$reflang = 'it-IT';
$LangtoTranslate = [ array of languages ]; => ex: ['en-GB','de-DE']
As it is unclear what you want to achieve since you only provide partial code I will have my own version of your code.
Instead of using find() you want to use the where() function.
$a = ["0","1","2"];
$b = [];
foreach($a as $text){
$found = Dictionary::where('YourColumn','=',$text)->first();
if($found !== null){
array_push($b,$found->YourColumn);
}else{
array_push($b, null);
}
}

How to loop number and saved into table laravel

I have input and this input is will generate number sequentially like this
5.01
5.02
5.03
......
5.10
5.11
i get number 5 on first number is from my another data . u can see at my code .so how i can do this if this number start from '01' not '1' and if more than 10 this '0' in first number is deleted.
in my controller i saved in $data and looping this number from 01
So in my input controller is like that :
public function store(Request $request)
{
$data = $request['kode_induk'] + // i dont know what to do here for loop this input ,
$induk = IndukBelanja::create([
'user_id' => Auth::user()->id,
'kode_induk' => $request['kode_induk'],
'kode_rekening' => $data,
'uraian' => $request['uraian'],
'anggaran' => $request['anggaran'],
]);
if ($induk) {
return ['redirect' => route('rekening_induk')];
} else {
return response()->json([
'success' => false,
'message' => ' Gagal update!',
], 500);
}
}
how i can loop this number ? can someone help ?
Update its my database what i need
+----+------------+------------+------------+
| id |kode_induk |kode_rekening| uraian
+----+------------+------------+------------+
| 1 | 5 | 5.01 | some data
+----+------------+------------+------------+
| 2 | 5 | 5.02 | some data
+----+------------+------------+------------+
| 3 | 5 | 5.03 | some data
+----+------------+------------+------------+
| 4 | 5 | 5.04 | some data
+----+------------+------------+------------+
You can cast $data to int and then increment by 0.01 in a for loop.
$data = (int) $request['kode_induk'];
$numberOfSequencesToGenerate = 10;
for($i = 0; $i < $numberOfSequencesToGenerate; $++){
$induk = IndukBelanja::create([
'user_id' => Auth::user()->id,
'kode_induk' => $request['kode_induk'],
'kode_rekening' => $data + 0.01,
'uraian' => $request['uraian'],
'anggaran' => $request['anggaran'],
]);
}
The loop basically reads, run the the block of code while $i is less than $numberOfSequencesToGenerate. On each iteration increment $i by one.
I am assuming the DB field kode_rekening is of type double but if is not you can format it in PHP so is always has two decimal places with number_format(). Ex: number_format($data + 0.01, 2)

comparing 2 data sets possibly with concurrency/asynchronous/parallel approach

I am currently trying to improve upon an existing mechanism (to compare data from 2 sources, implemented in perl5) and would like to use perl6 instead.
My target data volume range is about 20-30 GB in uncompressed flat files.
In terms of lines, a file can contain anywhere from 18 million to 28 million lines.
It has around 40-50 columns per line.
I do this type of data reconciliation on a daily basis and it can take about ~10 minutes to read from a file and populate the hash. ~20 minutes spent to read both files and to populate hash.
comparison process takes about ~30-50 minutes including iterating over hash, collecting desired result(s), and writing to output file (csv,psv).
All in all it can take anywhere between 30 minutes to 60 minutes on a 32 core dual xeon cpu server with 256gb of RAM, including intermittent server load, to perform the process.
Now I am trying to bring down the total processing time even further.
Here is my current single threaded approach using perl5.
fetch data from 2 sources (let's say s1 and s2) one by one and populate my hash based on key-value pairs. Source of data could be either a flat csv or psv file OR a database query Array of Array result, via DBI client. Data is always unsorted to start with.
To be specific, I read the file line by line,split fields, and choose desired indexes for key,value pair and insert into hash.
After collecting data and populating hash with desired key/value pairs,I start to compare and collect results (mainy comparing on what is missing or different in s2 w.r.t s1 and vice-versa).
dump output in an excel file (very costly if no. of lines is large like ~1 million or greater) or in a simple CSV (cheap operation. preferred method).
I was wondering whether if I could somehow do the first step in parallel i.e. collect data from both sources at once and populate my global hash, and then proceed to compare and dump output?
What options can perl6 provide to deal with this situation? I have read about concurrency, asynchronous and parallel operations using perl6 but I am not so certain which one can help me here.
I would really appreciate any general guidance on the matter. I hope I explained my problem well but sadly I don't have much to show for what have I tried till now? and reason is that I am just beginning to tackle this one. I am just unable to see past the single threaded approach and need some help.
Thanks.
EDIT
As my existing problem statement has been deemed by the community as 'too broad' - allow me to attempt to highlight my pain points below:
I would like to do file comparison by utilizing all 32 cores if possible. I am just not able to come up with a strategy or initial idea.
What type of new techniques are available or applicable with perl6 in order to tackle this problem or type of problem.
If I spawn 2 processes to read file(s) and collect data - is it possible to get the result back as an array or hash?
Is it possible to compare the data (stored in hash) in parallel?
My current p5 comparison logic is shown below for your reference. Hope this helps and not let this question shutdown.
package COMP;
use strict;
use Data::Dumper;
sub comp
{
my ($data,$src,$tgt) = #_;
my $result = {};
my $ms = ($result->{ms} = {});
my $mt = ($result->{mt} = {});
my $diff = ($result->{diff} = {});
foreach my $key (keys %{$data->{$src}})
{
my $src_val = $data->{$src}{$key};
my $tgt_val = $data->{$tgt}{$key};
next if ($src_val eq $tgt_val);
if (!exists $data->{$tgt}{$key}) {
push (#{$mt->{$key}}, "$src_val|NULL");
}
if (exists $data->{$tgt}{$key} && $src_val ne $tgt_val) {
push (#{$diff->{$key}}, "$src_val|$tgt_val")
}
}
foreach my $key (keys %{$data->{$tgt}})
{
my $src_val = $data->{$src}{$key};
my $tgt_val = $data->{$tgt}{$key};
next if ($src_val eq $tgt_val);
if (!exists $data->{$src}{$key}) {
push (#{$ms->{$key}},"NULL|$tgt_val");
}
}
return $result;
}
1;
If someone would like to try it out, here is the sample output and the test script used.
script output
[User#Host:]$ perl testCOMP.pl
$VAR1 = {
'mt' => {
'Source' => [
'source|NULL'
]
},
'ms' => {
'Target' => [
'NULL|target'
]
},
'diff' => {
'Sunday_isit' => [
'Yes|No'
]
}
};
Test Script
[User#Host:]$ cat testCOMP.pl
#!/usr/bin/env perl
use lib $ENV{PWD};
use COMP;
use strict;
use warnings;
use Data::Dumper;
my $data2 = {
f1 => {
Amitabh => 'Bacchan',
YellowSun => 'Yes',
Sunday_isit => 'Yes',
Source => 'source',
},
f2 => {
Amitabh => 'Bacchan',
YellowSun => 'Yes',
Sunday_isit => 'No',
Target => 'target',
},
};
my $result = COMP::comp ($data2,'f1','f2');
print Dumper $result;
[User#Host:]$
If you have an existing and working toolchain you don't have to rewrite it all to use Perl6. It's parallelism mechanisms work fine with external processess too. Consider
allnum.pl6
use v6;
my #processes =
[ "num1.txt", "num2.txt", "num3.txt", "num4.txt", "num5.txt" ]
.map( -> $filename {
[ $filename, run "perl", "num.pl", $filename, :out ];
})
.hyper;
say "Lazyness Here!";
my $time = time;
for #processes
{
say "<{$_[0]} : {$_[1].out.slurp}>";
}
say time - $time, "s";
num.pl
use warnings;
use strict;
my $file = shift #ARGV;
my $start = time;
my $result = 0;
open my $in, "<", $file or die $!;
while (my $thing = <$in>)
{
chomp $thing;
$thing =~ s/ //g;
$result = ($result + $thing) / 2;
}
print $result, " : ", time - $start, "s";
On my system
C:\Users\holli\tmp>perl6 allnum.pl6
Lazyness Here!
<num1.txt : 7684.16347578616 : 3s>
<num2.txt : 3307.36261498186 : 7s>
<num3.txt : 5834.32817942962 : 10s>
<num4.txt : 6575.55944995197 : 0s>
<num5.txt : 6157.63100049619 : 0s>
10s
Files were set up like so
C:\Users\holli\tmp>perl -e "for($i=0;$i<10000000;$i++) { print chr(32) ** 100, int(rand(1000)), chr(32) ** 100, qq(\n); }">num1.txt
C:\Users\holli\tmp>perl -e "for($i=0;$i<20000000;$i++) { print chr(32) ** 100, int(rand(1000)), chr(32) ** 100, qq(\n); }">num2.txt
C:\Users\holli\tmp>perl -e "for($i=0;$i<30000000;$i++) { print chr(32) ** 100, int(rand(1000)), chr(32) ** 100, qq(\n); }">num3.txt
C:\Users\holli\tmp>perl -e "for($i=0;$i<400000;$i++) { print chr(32) ** 100, int(rand(1000)), chr(32) ** 100, qq(\n); }">num4.txt
C:\Users\holli\tmp>perl -e "for($i=0;$i<5000;$i++) { print chr(32) ** 100, int(rand(1000)), chr(32) ** 100, qq(\n); }">num5.txt

Laravel overwrite value in request

I trouble to overwrite existing request value.
Below example info is my input array and product is my input array key.
e.g,
HTML
<input type="text" name="info[product]" value="10" />
PHP
echo request('info.product');
OUTPUT
10
Edit
print_r(request()->all());
Array
(
[info] => Array
(
[product] => 10
)
[_method] => PUT
[info.product] => 20
)
Question : But now I am required to overwrite this default 10 value to 20 using laravel.
Use the merge() method:
$array['input']['product'] = 20;
request()->merge($array);
Or do this when you'll need the data from request:
$data = request()->all();
$data['input']['product'] = 20;
Try this:
Input::merge(['input.product' => 'new value']);
and don't forget to import Input facade at the top.( use Input;)

SQL Query for Updating Rows with New Values from Temporary Table in Laravel/Eloquent

I wish to update table B based on source table A so that if a new record is found, we can insert it otherwise update the record if any values have changed. How would I write the query in laravel 4 using eloquent?
Table A Table B
======= =======
Name | Color Name | Color
---------------------- ----------------------
Mickey Mouse | grey Mickey Mouse | red
Donald Duck2 | green Donald Duck | blue
Donald Duck | blue Minnie | red
Goofy | black
Minnie | red
In this example table B should be inserted with the rows Goofy and Donald Duck2 and the row mickey mouse should be updated with the new color grey.
This should work:
$a = A::all();
foreach($a as $current)
{
$b = B::where("name", "=", $current->name)->first();
if(!$b) $b = new B;
if($b->name != $current->name)
{
$b->name = $current->name;
$b->save();
}
}
Or more optimized:
$a = A::all();
// using this script: http://stackoverflow.com/questions/12050892/array-mapping-in-php-w ith-keys
$aFolded = array_reduce($a, function(&$result, $item){
$result[$item->name] = $item->color;
return $result;
}, array());
// so we now have array ( name => color, name2 => color2 )
$b = B::with("a", "name")->get(); // might recheck with laravel doc
foreach($b as $updateMe)
{
if($updateMe->color != $aFolded[$b->name])
{
$updateMe->color = $aFolded[$b->name];
$updateMe->save();
unset($aFolded[$b->name]);
}
}
// after this $aFolded will only contain the names which do not exist in b so we can just insert them all (maybe the insert query could be better)
foreach($aFolded as $name => $color)
{
DB::table("B")->insert(array("name" => $name, "color" => $color));
}

Resources