this is not duplicate but related to the topic Query inside for loop in laravel
Is this the correct code in laravel for putting query inside the loop
//controller
public function dtrdata()
{
for($i=1;$i<=$totalnumdays;$i++){
$query= DB::table('dtrrecords')
->where('dtrrecords.bio_id', $i)
}
return view('pages/admin.dtrdata', compact('query','i'));
}
//view
#foreach($query as $row => $rows1)
<tr>
<td>{{$rows1->AM_IN}}</td>
</tr>
#endforeach
There are a couple problems with your loop. First you are overwriting the $query variable on each iteration. Second, you need to call ->get() to execute the query and return results. The following illustrates how to add multiple query results into a single collection and then loop the results in the view:
public function dtrdata()
{
$collection = collect();
for($i=1;$i<=$totalnumdays;$i++){
$records = DB::table('dtrrecords')->where('dtrrecords.bio_id', $i)->get();
$collection->concat($records)
}
return view('pages/admin.dtrdata', compact('collection'));
}
#foreach($collection as $item)
<tr>
<td>{{ $item->AM_IN} }</td>
</tr>
#endforeach
You can do your job by another solution without looping:
public function dtrdata()
{
// Make an array from 1 to $totalnumdays using php range function
// follow the link for range function https://www.w3schools.com/php/func_array_range.asp
$numDays = range(1,$totalnumdays);
$query= DB::table('dtrrecords')
->whereIn('dtrrecords.bio_id', $numDays) // Use laravel whereIn method
->get();
return view('pages/admin.dtrdata', compact('query'));
}
//view
#foreach($query as $row => $rows1)
<tr>
<td>{{$rows1->AM_IN}}</td>
</tr>
#endforeach
Related
I am trying to get the total of the column Price with condition BillPaid column value should be 0.
My code block is
public function countDue()
{
$getTotalDue = DB::table('ordered_books')
->where('BillPaid', 0)
->sum('Price')
->get();
return response()->json($getTotalDue);
return compact('getTotalDue');
}
controller code block for calling the countDue method.
public function create()
{
return view('pages.booksin', $this->countDue());
}
view page
<table id="showBooksIn" class="table table-bordered gridview">
<thead>
<tr><th>Total Due Amount</th></tr>
</thead>
<tbody>
#if(isset($getTotalDue))
#foreach($getTotalDue as $data)
<tr>
<td> {{$data}} </td>
</tr>
#endforeach
#endif
</tbody>
</table>
but I am getting error as :
Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR)
Call to a member function get() on float
My table structure is:
From Laravel's documentation, you don't need to chain the get() method there.
public function countDue(){
$getTotalDue = DB::table('ordered_books')->where('BillPaid', 0)->sum('Price'); //Get the sum using the Laravel's query builder aggregate sum method
return $getTotalDue;
}
public function create()
{
return view('pages.booksin', ['getTotalDue' => $this->countDue()]); //Pass the `countDue()` method output to the view
}
Note
This is a single value, you might want to display it inside a header or paragraph element like so:
#if(isset($getTotalDue))
<h2>{{ $getTotalDue }}</h2>
#endif
You don't need the get() method in there.
public function countDue()
{
$getTotalDue = DB::table('ordered_books')
->where('BillPaid', 0)
->sum('Price');
return response()->json($getTotalDue);
return compact('getTotalDue');
}
Also, you have two return statements right after another, making the second one unreachable.
The second argument of the view() method needs to be an array, or you could use the with() syntax. You should try the following code, and passing the $getTotalDue into the view.
public function create()
{
$getTotalDue = DB::table('ordered_books')
->where('BillPaid', 0)
->sum('Price');
return view('pages.booksin')->with(['getTotalDue' => $getTotalDue]);
}
No need to use get()
$getTotalDue = DB::table('ordered_books')
->where('BillPaid', 0)
->sum('Price');
will return a float with your sum value
What i want to achieve here is to return a string to my view in laravel, but i what i got is this error
"Undefined variable: tod (View:
C:\xampp\htdocs\blog\resources\views\opj_view.blade.php)"
and here is my controller look liked :
public function index()
{
$tod = 'test';
$user = DB::select('select * from tbluser where ID like ?',['%USER%']);
return view('opj_view',['user '=>$user ],['tod'=>$tod]);
}
and here is my view looked like :
<body>
<?php echo $tod; ?>
<div>User</div>
<table border = 1>
<tr>
<td>User ID</td>
<td>Username</td>
</tr>
#foreach ($user as $users)
<tr>
<td>{{ $users->ID }}</td>
<td>{{ $users->User_Name }}</td>
</tr>
#endforeach
</table>
</body>
How to print out $tod variable properly? Because when I delete my ['tod'=>$tod] it works, it just string but it said Undefined Variable, I am newbie in PHP, is there some way to declare variable? from what i read may way is true.. please need help guys
Change
return view('opj_view',['user '=>$user ],['tod'=>$tod]);
To
return view('opj_view',['user' => $user, 'tod' => $tod]);
You can read the documentation about Passing Data To Views
From the docs and experiance
return view('opj_view',compact('tod,'user'));
Or
return view('opj_view',['user '=>$user,'tod'=>$tod ]));
Or
return view('opj_view')->with(['user '=>$user,'tod'=>$tod]);
You're passing two arrays to the view, you just need to have tod as an index in the same array:
public function index()
{
$tod = 'test';
$user = DB::select('select * from tbluser where ID like ?',['%USER%']);
return view('opj_view',['user '=>$user, 'tod'=>$tod]);
}
You can simply use:
return view('opj_view')->with('user', 'tod');
In my database I have many to many relation between notifications and statuses table. So the pivot table stored the notification_id, statuses_id and values. Now, in my model I wrote a function historysStatus, which extracts that values and created_at from pivot table
public function historystatus()
{
$o_status = Status::where('name','health')->first();
$o_response = $this->statuses()->where('status_id', $o_status->id)
->select('values','created_at')->first();
if($o_response === null){
return false;
}
return ['value' => $o_response->values,
'timestamp' => $o_response->created_at];
}
I want to iterate through all the values and timestamps associated with a specific notification.thus in blade I wrote the for each loop to iterate through all values and created at.
#foreach($notes as $notification)
<?php $notificationHealth = $notes->historystatus('health'); ?>
<tr>
<td>{{ $notificationHealth['timestamp'] }}</td>
<td> {{ $notificationHealth['value'] }}</td>.
</tr>
#endforeach
</tbody>
instead it gave me only the last record 4 times. Is something wrong with the sql query? I would appreciate any suggestion and ideas?
Inside the foreach try using $notification->historystatus('health'); instead of $notes->historystatus('health');
#foreach($notes as $notification)
<?php $notificationHealth = $notification->historystatus('health'); ?>
<tr>
<td>{{ $notificationHealth['timestamp'] }}</td>
<td> {{ $notificationHealth['value'] }}</td>.
</tr>
#endforeach
public function history($s_type)
{
if (!in_array($s_type, ['speed', 'health'])){
return false;
}
$o_status = Status::where('name', strval($s_type))->first();
$o_response = $this->statuses()->where('status_id', $o_status->id)
->select('values', 'created_at')->orderBy('created_at','DESC')->get();
if($o_response === null || $o_response->count() === 0){
return false;
}
$a_ret = [];
foreach ($o_response as $o_status) {
$a_ret[] = [
'value' => $o_status->values,
'timestamp' => $o_status->created_at
];
}
return $a_ret;
}
this is the simple answer i figured out. and the foreach loop in side the blade.
i have a problem about looping data in controller (laravel 4). my code is like this:
$owner = Input::get('owner');
$count = Input::get('count');
$product = Product::whereOwnerAndStatus($owner, 0)->take($count)->get();
when i want to use foreach to loop for $product result with code like this:
foreach ($product->sku as $sku) {
// Code Here
}
the result is returning error
Undefined property: Illuminate\Database\Eloquent\Collection::$sku
so, i try to improvise a little with this code:
foreach ($product as $items) {
foreach ($items->sku as $sku) {
// Code Here
}
}
the code returning error like this:
Invalid argument supplied for foreach()
is there someone who could help me solve this?
This will throw an error:
foreach ($product->sku as $sku){
// Code Here
}
because you cannot loop a model with a specific column ($product->sku) from the table.
So, you must loop on the whole model:
foreach ($product as $p) {
// code
}
Inside the loop you can retrieve whatever column you want just adding ->[column_name]
foreach ($product as $p) {
echo $p->sku;
}
Actually your $product has no data because the Eloquent model returns NULL. It's probably because you have used whereOwnerAndStatus which seems wrong and if there were data in $product then it would not work in your first example because get() returns a collection of multiple models but that is not the case. The second example throws error because foreach didn't get any data. So I think it should be something like this:
$owner = Input::get('owner');
$count = Input::get('count');
$products = Product::whereOwner($owner, 0)->take($count)->get();
Further you may also make sure if $products has data:
if($product) {
return View:make('viewname')->with('products', $products);
}
Then in the view:
foreach ($products as $product) {
// If Product has sku (collection object, probably related models)
foreach ($product->sku as $sku) {
// Code Here
}
}
The view (blade template): Inside the loop you can retrieve whatever column you looking for
#foreach ($products as $product)
{{$product->sku}}
#endforeach
Is sku just a property of the Product model? If so:
$products = Product::whereOwnerAndStatus($owner, 0)->take($count)->get();
foreach ($products as $product ) {
// Access $product->sku here...
}
Or is sku a relationship to another model? If that is the case, then, as long as your relationship is setup properly, you code should work.
$allData = Model::where('status', 1)->get();
foreach ($allData as $data){
$data->status = 0;
$data->update();
}
Here every $data is single data and $allData contains full collection.
using foreach on table
for me
#foreach($products as $data)
<tr>
<td>{{$data->id}}</td>
<td>{{$data->name}}</td>
<td>{{$data->price}}</td>
</tr>
#endforeach
Edit multiple data in laravel
You can use this for updating multiple data in laravel, which i have tested it and it works for me.
also remember i used relatationship here
I have a typical model relation. I have the model QR, which hasMany Rating, and a Model Rating, which belongsTo Qr.
Now I want to output the Ratings, which belong to a single qr model, through a foreach loop like this:
<table>
<tr>
<th>ID</th>
<th>UnitID</th>
<th># of Ratings</th>
</tr>
#foreach($qrs as $qr->ratings)
<tr>
<td>{{$qr->id}}</td>
<td>{{$qr->unit_id}}</td>
<td>{{$qr->ratings->count()}}</td>
</tr>
#endforeach
</table>
This is my Controller:
public function index()
{
//
$unit = Unit::all()->first();
$qrs = Qr::all()->first();
return View::make('index')
->with('unit', $unit)
->with('qrs', $qrs);
}
Here are my two Models
Rating.php:
class Rating extends \Eloquent {
protected $guarded = [];
public function qr(){
return $this->belongsTo('Qr');
}
}
Qr.php:
class Qr extends \Eloquent {
protected $guarded = [];
public function unit(){
return $this->belongsTo('Unit');
}
public function ratings(){
return $this->hasMany('Rating');
}
}
I actually want to output the count of ratings, a Qr-Code has. I know it is possible to do it somehow like this:
{{Rating::where('qr_id', $qr->id)->count()}}
But I want to do it somehow like this in the foreach loop
{{ $Qr->rating->count() }}
If this is somehow possible.
I get the relation, if I just output the first() of Qr and then
var_dump($qrs->ratings->toArray())
But I don't know how to get the count Number of ratings in combination with the foreach loop. Any help would be dearly appreciated.
Couple of things wrong here:
// view:
#foreach($qrs as $qr->rating)
// should be:
#foreach($qrs as $qr)
// controller:
$unit = Unit::all()->first();
$qrs = Qr::all()->first();
// this way you get all Units then fetch first Unit from the collection,
// the same with Qrs, so change it to:
$unit = Unit::all(); // do you need it at all?
$qrs = Qr::with('ratings')->get();
This will solve the problem and in the foreach loop you will be able to access $qr->ratings->count() which will be Collection method.
At first you have used this:
#foreach($qrs as $qr->ratings)
You need to change it to this (as already stated in an answer):
#foreach($qrs as $qr)
Then in your index method you have used this:
public function index()
{
$unit = Unit::all()->first();
$qrs = Qr::all()->first();
return View::make('index')->with('unit', $unit)->with('qrs', $qrs);
}
In this case you need to get a collection of QR models and since Unit and Rating are related to Qr then you may use with and get() to get a collection of QR models like this:
public function index()
{
$qrs = Qr::with(array('unit', 'ratings'))->get();
return View::make('index')->with('qrs', $qrs);
}
Then you'll be able to loop the Qr models in your view like this:
#foreach($qrs as $qr)
<tr>
<td>{{ $qr->id }}</td>
<td>{{ $qr->unit_id }}</td>
<td>{{ $qr->ratings->count() }}</td>
</tr>
#endforeach