I was wondering whether I could do an if statement for each iteration through the array. This is so that I can punctuate each user with either a ',' or an '&' depending on how many users.
#foreach ($copy as $user => $value)
#if ($user == 0)
{{$value->username}}
#endif
#if ($user == 1)
, {{$value->username}}
#endif
#if ($user == 2)
, {{$value->username}}
#endif
#if ($user == 3)
& {{$value->username}}
#endif
#endforeach
The code above punctuates correctly if there are 4 users but what if I have less than 4. How would I move the '&' to the 3rd user if there were 3 users for example?
When faced with issues such as this, try to find the most optimal solution. In this case you can determine that you need the comma in all but two places and the ampersand in one. So instead of having a condition for each array index, you should place one for commas and one for the ampersand:
#foreach ($copy as $user => $value)
{{$value->username}}
// Place commas after all but the last two items
#if ($user < count($copy) - 2)
,
#endif
// Place an ampersand before the last item
#if ($user == count($copy) - 2)
&
#endif
#endforeach
This will work with a list of any size.
Related
So the dd of a query is shown below
Whenever I try to get the value of totalsales, I get 0. My query:
$this->query = Sales::with(['item', 'branch'])->isSales()->groupBy('item_id')
->select(DB::raw('count(*) as total, SUM(costs) as costs,SUM(profit) as profits, SUM(selling_price) as totalsales,item_id'))->orderBy('total','DESC');
$this->query = $this->query->whereBetween('date',[$this->start_date,$this->end_date]);
$qq = $this->query;
$sales = $this->query->paginate($this->perPage);
and I output the value in a table cell in blade as follows:
<td>
{{ number_format($sale->totalsales, 3) }}
</td>
Note: all other attributes are displaying correctly
Thank you
Trying to write the cleanest code in Blade of a foreach where in the position 3 (if first and second exists) add a different code.
I'm trying using chunk() but it doesnt allow do non regulars array.
Write position 1 if exists
Write position 2 if exists with different class
Write some content between array position 2 and 3 from different array
Write position 3 if exists
Write position 4 if exists with different class
...
why u use chunk? u can use $key
#foreach($arr as $key => $value)
#if ($key === 2)
do something
#endif
#endforeach
or
#for ($i = 0; $i < count($arr); $i++)
#if ($i === 2)
do something
#endif
#endfor
How can i get sum of all these counts?
{{ DB::table('A')->count()}}
{{ DB::table('B')->count()}}
{{ DB::table('C')->count()}}
{{ DB::table('D')->count()}}
// Your Tables Which You Know Them Counts
$tables = ['A', 'B'];
// Our Count Start From Zero
$count = 0;
// Count Each Table And Add Our Count
foreach ($tables as $table) {
$tableCount = DB::table($table)->count();
$count += $tableCount;
}
// Display Count With dd()
dd( $count );
// Or Display In View
return view('index', compact('count'));
Like this?:
{{ $a = DB::table('A')->count()}}
{{ $b = DB::table('B')->count()}}
{{ $c = DB::table('C')->count()}}
{{ $d = DB::table('D')->count()}}
{{ $sum = $a + $b + $c + $d }}
But you may want to send all these data from a controller method instead of doing it in a view.
I am trying to group my results by date. My date field is a mySQL timestamp and I am using Laravel 4.1. For the purpose of this, I am using a field named 'start_time' and need it to group literally by date only, disregarding the actual time.
Can anyone point me in the right direction? I am unfamiliar with using dates like this in this framework.
$agenda = Agenda::where('active', '=', 'Y');
$agenda->with('user');
$agenda->with('room');
$agenda->groupBy(DB::raw('DATE_FORMAT(start_time, "%d/%m/%Y")'));
$agenda->orderBy('start_time', 'asc');
$agenda->distinct();
$agenda->get();
return View::make('agenda')->with('agendas', $agenda);
#foreach($agendas as $agenda)
{{ date("d M Y",strtotime($agenda->start_time)) }}
#endforeach
This may be a very basic approach but that's how I always do it:
<?php $currentDate = null ?>
#foreach($agendas as $agenda)
<?php $date = date("d M Y",strtotime($agenda->start_time)); ?>
#if($currentDate != $date)
<?php $currentDate = $date; ?>
<h3>{{ $date }}</h3>
#endif
{{-- do the stuff --}}
#endforeach
It would be nice (and best/better practice) not to do the date formatting like this in the view. But you get the idea.
May be you would split to more foreach loop (?) .
At first, we will query to get all of start_time with distinct, order, eta...
Then, push a foreach loop to get data belonged to each start_time element.
Hope this will be usefull.
I am creating an order cart.
On the page that displays the cart, it checks if a value stored in the session $order corresponds with an id of a row in a mysql table. If this match exists, then the corresponding row is returned.
Within this process, I am trying to retrieve the quantity value stored in the session $quantity that corresponds to the id of the row in the table.
Each value in $order and $quantityis assigned a name, which is the id of the item they were added from.
This is the code that adds the order to the cart:
if (isset($_POST['action']) and $_POST['action'] == 'Order')
{
// Add item to the end of the $_SESSION['order'] array
$_SESSION['order'][$_POST['id']] = $_POST['id'];
$_SESSION['quantity'][$_POST['id']] = $_POST['quantity'];
header('Location: .');
exit();
}
This is the code on the cart page:
foreach ($order as $item)
foreach ($quantity as $amount)
{
mysql_data_seek( $productsSql, 0); //<- this line, to reset the pointer for every EACH.
while($row = mysql_fetch_assoc($productsSql))
{
$itId = $row['id'];
$itDesc = $row['desc'];
$itPrice1 = $row['price1'];
if ($item == $itId)
{
$pageContent .= '
<tr>
<td>'.$itDesc.'</td>
<td>'.if ($item[''.$itId.''] == $amount[''.$itId.'']) {echo $amount}.'</td>
<td>R'.number_format($itPrice1*$amount, 2).'</td>
</tr>
';
}
}
}
This row is producing a syntax error:
<td>'.if ($item[''.$itId.''] == $amount[''.$itId.'']) {echo $amount}.'</td>
What is the problem here for starters?
Secondly, how would I need to do to accomplish the task that I am facing?
Any input on this would be greatly appreciated!
Could you try this?
<td>'.($item[$itId] == $amount[$itId] ? $amount : '').'</td>
This is a ternary operator, look at http://en.wikipedia.org/wiki/Ternary_operation
You can't simply add conditional statements like that while you're building a string.
You can do this, however
<td>' . ($item[$itId] == $amount[$itId]) ? $amount : null . '</td>
but you should use a more legible method.
Another issue you may get is if $amount is an array, you won't be able to print it as a string. If, however, $amount is an object with ArrayAccess interface, you can print it with the __toString() method; but that's another story.
The code for creating the cart page has several issues.
You walk over items and over quantities, which will probably give you duplicate outputs.
$item is a plain string, so I wonder what $item[$itId] is supposed to do?
You walk over your complete result set several times which actually is not necessary. I really hope that "$productSql" isn't a "select * from product", otherwhise this might get REAL slow in production mode.
I suggest creating a good SQL for getting the data and using this as a basis for filling the page:
// note this has SQL-injection issues, so you really need to make sure that $order contains no crap
$productsSql = mysql_query("select * from product where id in (".join($order, ',').")");
// you now have a result set with all products from your order.
while($row = mysql_fetch_assoc($productsSql))
{
$itId = $row['id'];
$itDesc = $row['desc'];
$itPrice1 = $row['price1'];
// session contains the quantity array mapping ID -> Quantity, so grab it from there
$itQuantity = $quantity[$itId];
// finally calculate the price
$itPrice = number_format($itPrice1*$itQuantity, 2);
// now you have all data for your template and can just insert it.
// if you use double quotes you can put the $xyz into the string directly
$pageContent .= "
<tr>
<td>$itDesc</td>
<td>$itQuanty</td>
<td>R $itPrice</td>
</tr>
";
}