How to write for Each Loop in Laravel - laravel

Laravel Code to connect with Database
In $response i have array of items. These items may or may not be present in dishOrder table.
I have to Count the no of orders of each item which is under itemQuantity Column in dishOrder Table.
How to write For Loop for this.?

Do you want to loop in blade or in the backend? This is how you generally do loops on arrays / collections.
In backend:
foreach( $response as $item ) {
// do stuff with $item
}
If you want to display the count in the frontend
#foreach( $response as $item )
<h1>{{ $item->title }}</h1> <!-- if you have a title -->
<h2>{{ count( $item->innerArray ) }}</h2>
<h3>{{ $item->itemQuantity }}</h3>
#endforeach
However to be more specific regarding your problem you will need to provide more information or even better the code of what you already tried

As far as I understand you want to create an SQL-Query which looks like this in MySQL:
SELECT sum(itemQuantity), itemName FROM dishOrder where itemName in ('soup','pizza','burger');
Laravel has the whereIn method to create such a query. Example from the manual (https://laravel.com/docs/5.2/queries):
$users = DB::table('users')
->whereIn('id', [1, 2, 3])
->get();

Related

Show collection of data using while loop

How can I show collection of data using while loop in blade file? Suppose I have some data like this
$products = Product::latest()->where('status', 1)->get();
return view('products', compact('products'));
Now in this case how can I write this $products variable in my products.blade.php file.? I don't wana use #foreach loop. Can anybody help me.?
You can use Laravel Collection's get method to retrieve a 'row' at a given key.
#php $i=0; #endphp
#while($i < $products->count())
{{ $products->get($i)->name }}
#php $i++; #endphp
#endwhile

How to load multiple number of pages dynamically in laravel?

I have this table instruction_title and this table instruction_body. One instruction title can have one or many instruction body. In my resource controller instController the index funtion is showing the list of instruction title, onclick it is going to the show function and showing which bodies it has.
If the instruction id is 25, it is going to /instructions/25.
But I need something like /instructions/25/Body1 with a next button if it has body2 and on next it will go to /instructions/25/Body2 and go on.
You can do something like this :
in your routes :
Route::get('/instructions/{titleId}/{bodyName}', 'instController#index')->name('titleIndex');
And in your blade :
#php
$currentBodyId = $next = \DB::table('instruction_body')
->orderBy('id', 'asc')->select('id')
->first();
$next = \DB::table('instruction_body')
->where('titleId', $YOUR_TITLE_ID)
->where('id', '>', $currentBodyId)
->sortBy('id')
->first();
$nextUrl = ($next !== null) ? $next->YOUR_BODY_NAME : '#' ;
#endphp
And in your next button in blade:
#if ($nextUrl != '#')
<a href="{{ route('titleIndex', ['bodyName' => $nextUrl]) }}">
Next
</a>
#endif
#behnam's has some bad practice. Never have logic to query data in the presentation layer! That was the reason why MVC architecture was built.
But what you could do is attach a relationship one-to-many for both Models:
Read here
Then you can fetch bodies that belongs to a specific title like:
//in your controller
$datas = Title::find(25)->with('bodies');
Then you can loop through it to get the id.

How do I parse this json data in view blade? Output [{"...":...}]

I am trying to display the maximum value of an attribute in a table
my controller
$member = DB::table('member')
->select(DB::raw('MAX(code) as code'))
->where('status', '=', "No")->get();
return view('member.index', compact('member'));
Currently this is my view
{{ $member }}
And this is the output
[{"code":14101234}]
I wanted to display something like this
14101234
I've tried using json_decode but the result remains.
You receive a collection there, so you will have to do
#foreach($member as $item)
{!! $item->code !!}
#endforeach
Since $member is a array of object you are getting in view.
So you can fetch a object key by -> operator. you can fetch code like this. since you are doing ->get(), so it will return array of object.
#foreach($member as $m)
{{ $m->code }}
#endforeach
$member is a collection object.You can iterate through it to get the value in your view.
example: (in view.blade.php)
#foreach($member as $individual)
{{$individual->code}}
#endforeach
this would give you the value as you want

htmlentities() expects parameter 1 to be string, array given? Laravel

I've found many question realated to my problem but couldn't found an answer yet. It's about my foreach loop in my blade.
I want to print all product-names in my blade but I couln't figure out how to do that.
thats how I'm getting the products:
--- current code:
// controller
$id_array = Input::get('id');
$products= Products::whereIn('id', $id_array)->get();
$product_name = [];
foreach($products as $arr)
{
$product_name= $arr->lists('name');
}
returning $product_name gives me this as a output:
["football","cola","idontknow","freshunicorn","dummy-data"]
In my blade is just a simple:
#foreach($products as $product)
{{ $product}}
#endforeach
Error: htmlentities() expects parameter 1 to be string, array given
Thanks for your help and time.
It seems you are getting an object in an array in an array.
Like this:
array(
array(
object
)
)
It happens because you use the get() function to retrieve you model. The get() function always "wants" to retrieve multiple models. Instead you will have to use the first() function.
Like this:
foreach($id_array as $arr)
{
$want2editarray[] = Product::where('id', $arr)->first();
}
Hope it helps :)
Edit after #Wellno comment
That's probably because Product::where('id', $arr)->first(); returns null because it did not find anything.
I forgot to add a check after the retrieving of the product.
This can be done like this:
foreach($id_array as $arr)
{
// First try to get model from database
$product = Product::where('id', $arr)->first();
// If $product insert into array
if ($product) $want2editarray[] = $product;
}
Why do you use loop with IDs? You can find all products by IDs:
$products = Product::whereIn('id', $id_array)->get();
And then use $products in the blade template
#foreach($products as $product)
{{ $product->name }}
#endforeach
try to use Model/Eloquent to fetch data.
View should only display the data and not fetching directly from DB or do heavy calculations.

Assigning a variable to each row from a Get query

In my controller, I'm selecting all rows from a table, lets call it Users.
$users = User::get();
Let's say I want to assign a variable to each row from the Users table, that determines how old they were 10 years ago
I'm assuming I have to use a foreach
foreach ($users as $user) {
$decadeAgo = $user->age - 10;
}
Now in my blade, how can I display each user row, while also displaying the $decadeAgo variable?
try this as official laravel suggestion for blade templates:
#foreach ($users as $user)
<p>{{ $user->age - 10 }}</p>
#endforeach
You can iterate over the results and address each object by reference:
foreach ($users as &$user) {
$user->decadeAgo = $user->age - 10;
}
Then, in your blade template you will have access to the element you created on the $user object.
{{ $user->decadeAgo }}

Resources