How to display all row in database - Laravel 5.2? - php

I have simple issue with my Laravel application.But i can not find any solution of it.Please see my code here:
controller:
public function index(){
$members = Member::paginate(15);
$meal_entry = Member::all();
$breakfast = DB::SELECT("SELECT self_meal_breakfast + guest_meal_breakfast AS breakfast FROM meal_entry");
$lunch = DB::SELECT("SELECT self_meal_lunch + guest_meal_lunch AS lunch FROM meal_entry");
$dinner = DB::SELECT("SELECT self_meal_dinner + guest_meal_dinner AS dinner FROM meal_entry");
$total_meal = DB::SELECT("SELECT self_meal_breakfast + self_meal_lunch + self_meal_dinner + guest_meal_breakfast + guest_meal_lunch + guest_meal_dinner AS total FROM meal_entry");
return view('member.mealView', compact('members','data','breakfast','lunch','dinner','meal_entry','total_meal'));
}
blade view:
<tbody>
<tr>
#foreach($meal_entry as $value)
<td>{{ $value->created_at }}</td>
#endforeach
#foreach($breakfast as $value)
<td>{{ $value->breakfast }}</td>
#endforeach
#foreach($lunch as $value)
<td>{{ $value->lunch }}</td>
#endforeach
#foreach($dinner as $value)
<td>{{ $value->dinner }}</td>
#endforeach
#foreach($total_meal as $value)
<td>{{ $value->total }}</td>
#endforeach
#foreach($meal_entry as $value)
<td>{{ $value->created_at }}</td>
#endforeach
</tr>
</tbody>
And the table: meal_entry.
If there is a one row in the database then its ok ( see ) to view.But when there is row more than one then its show in one row with all data( see ).How can i handle this things? I think it should be run another loop but how can i do that? Thanks in advance.

So, if you're using Laravel, one of the best features that has is the accessors:
https://laravel.com/docs/5.2/eloquent-mutators#accessors-and-mutators
You can create new attributes and use them as model attributes.
For some stuff are very useful.
class Meal extends Model
{
public function getTotalBreakfastAttribute()
{
return $this->self_meal_breakfast + $this->guest_meal_breakfast;
}
}
And then, use this accessor as attribute:
<tbody>
#foreach($foods as $value)
<tr>
<td> {{$value->total_breakfast}} </td>
<td> {{$value->created_at}} </td>
</tr>
#endforeach
</tbody>
Or if you don't want to do that, instead of use multiple queries to get the data, just use one because all the fields are in the same table, and then, you could use the above example.
Enjoy! :)

A quick patch would be to do only one query and then do the calculations on the view (I know that is not a good practice to do the calculations in the view, but is the easiest way that i can see).
It would be like this:
Controller:
public function index(){
$members = Member::paginate(15);
return view('member.mealView', compact('members'));
}
blade view
<tbody>
#foreach($members as $meal_entry)
<tr>
<td>{{ $meal_entry->created_at }}</td>
<td>{{ $breakfast = $meal_entry->self_meal_breakfast + $meal_entry->guest_meal_breakfast }}</td>
<td>{{ $lunch = $meal_entry->self_meal_lunch+ $meal_entry->guest_meal_lunch}}</td>
<td>{{ $dinner = $meal_entry->self_meal_dinner + $meal_entry->guest_meal_dinner }}</td>
<td>{{ $breakfast + $lunch + $dinner }}</td>
<td>{{ $meal_entry->created_at }}</td>
</tr>
#endforeach
</tbody>
And remember to add
{{ $members->links() }}
Where you want the pagination links.

Related

How to use pluck to get specific data from other table in Laravel?

From SalesController, I want to get specific name from table Item and passed to HTML.
My controller looks like
public function index()
{
$items=Item::orderBy('name','ASC')->get()->pluck('name','id');
$sales=Sale::all();
return view('Sale.index')->with('sales',$sales,'items',$items);
}
My HTML is
<thead>
<tr>
<th>No</th>
<th>Name</th>
<th>Quantity</th>
<th>Total Price</th>
<th>Detail</th>
</tr>
</thead>
<tbody>
#foreach($sales as $sale)
<tr>
<td>{{ $sale->id }}</td>
<td>{{ $sale->items->name }}</td>
<td>{{ $sale->quantity }}</td>
<td>RM {{ $sale->price }}</td>
<td>{{ $sale->created_at }}</td>
</tr>
#endforeach
</tbody>
But I get the following error after trying to access the page:
Trying to get property 'name' of non-object (View: C:\xampp\htdocs\inventoryApp\resources\views\Sale\index.blade.php)
there are two way
1.Using relationship
class Sale extends Model
{
public function item()
{
return $this->belongsTo('App\Item','item_id','id');
}
}
so you can use like below
<td>{{ $sale->item->name }}</td>
2. Using array data
public function index()
{
$items=Item::orderBy('name','ASC')->pluck('name','id')->toArray();
$sales=Sale::all();
return view('Sale.index')->with('sales',$sales,'items',$items);
}
<td>{{ $items[$sale->item_id] }}</td>
$items=Item::orderBy('name','ASC')->pluck('name','id');
and use $items directly without sale object
If you have relationship with table Sale.
Add this function to your Sale Class.
public function item()
{
return $this->belongsTo('App\Item');
}
In your controller you can use compact
public function index()
{
$items=Item::orderBy('name','ASC')->get();
$sales=Sale::all();
return view('Sale.index')->compact('sales','items');
}
And you can use Eager load to your HTML.
<tbody>
#foreach($sales as $sale)
<tr>
<td>{{ $sale->id }}</td>
<td>{{ $sale->item->name }}</td>
<td>{{ $sale->quantity }}</td>
<td>RM {{ $sale->price }}</td>
<td>{{ $sale->created_at }}</td>
</tr>
#endforeach
</tbody>
You are getting this error because you are trying to get a property of item name that does not exist on the sale object. you can simply do it by eloquent relationship as follows:
On your sale model:
public function item()
{
return $this->belongsTo('App\Item','item_id');
}
On your controller:
public function index()
{
$sales=Sale::all();
return view('Sale.index',compact('sales'));
}
Then on your blade you can easily get related Item name:
#foreach($sales as $sale)
<tr>
<td>{{ $sale->item->name }}</td>
</tr>
#endforeach

Get dynamic values ​of dynamic arrays in a mode

I want to obtain the data of an Audit model, that within its columns old_values ​​and new_values ​​are stored arrays, but dynamic. When I do the foreach in the view it gives me the following error when wanting to show these columns:
ErrorException (E_ERROR) htmlspecialchars() expects parameter 1 to be string, array given (View: H:\DAF\resources\views\audit\index.blade.php)
I've already searched several blogs and they say how to do something similar but with static arrays, not with dynamic ones.
The Audit model is Laravel's vendor to audit called OwenIt\Auditing.
class Audit extends Model implements \OwenIt\Auditing\Contracts\Audit
{
use \OwenIt\Auditing\Audit;
/**
* {#inheritdoc}
*/
protected $guarded = [];
/**
* {#inheritdoc}
*/
protected $casts = [
'old_values' => 'json',
'new_values' => 'json',
'auditable_id' => 'integer',
];
}
Controller
<?php
namespace App\Http\Controllers;
use OwenIt\Auditing\Models\Audit;
class EstaticasController extends Controller {
public function audit() {
$audit = Audit::orderBy( 'id', 'DESC' )->get();
return view( 'audit.index', compact( 'audit' ) );
}
}
Vista
<table class="table table-bordered table-hover table-stripped">
<thead>
<tr>
<th>No</th>
<th>Operación</th>
<th>Tupla</th>
<th>Tabla</th>
<th>Valores antiguos</th>
<th>Valores Actuales</th>
<th>URL</th>
<th>IP</th>
<th>Creado</th>
<th>Actualizado</th>
</tr>
</thead>
<tbody>
<?php $no = 1 ?>
#foreach($audit as $item)
<tr>
<td>{{ $no++ }}</td>
<td>{{ $item->event }}</td>
<td>{{ $item->auditable_id }}</td>
<td>{{ $item->auditable_type }}</td>
<td>{{ $item->old_values }}</td>
<td>{{ $item->new_values }}</td>
<td>{{ $item->url }}</td>
<td>{{ $item->ip_address }}</td>
<td>{{ $item->created_at }}</td>
<td>{{ $item->updated_at }}</td>
</tr>
#endforeach
</tbody>
</table>
Image of Table
Image of DB with data
I think here is the issue:
// ...
// <td>{{ $item->auditable_type }}</td>
<td>{{ $item->old_values }}</td>
<td>{{ $item->new_values }}</td>
// <td>{{ $item->url }}</td>
// ...
The problem here is that, in order to print them in screen, the front-end is expecting the value to be string, but you are giving it an array. That's why the error is throw:
ErrorException (E_ERROR) htmlspecialchars() expects parameter 1 to be string, array given (View: H:\DAF\resources\views\audit\index.blade.php)
To solve it, you just have to iterate over the array to print every element of it:
#foreach ($item->old_values as $value)
<p>{{ $value }}</p>
#endforeach

Adding columns in table

I have display quantity and price attributes on my table from database but for some reasons I don't save the total into database but I display total by multiplying quantity * total on the table when data is being fetched.
Total for every column on my table is being displayed accurately. Is there a way that I can add all total columns on the table in my html?
PS: with my code, it only displays the total of the current column of the table
Table
<tbody>
#foreach($items as $items)
<tr>
<td>{{$item>id }}</td>
<td>{{$item->quantity}}</td>
<td>{{ $item->price}}</td>
<td>{{ $item->quantity * $item->price}}</td>
</tr>
#endforeach
<p>Sum: {{ $item->quantity * $item->price}}</p>
</tbody>
<tbody>
{{ $total = 0 }}
#foreach($items as $items)
<tr>
<td>{{$item>id }}</td>
<td>{{$item->quantity}}</td>
<td>{{ $item->price}}</td>
<td>{{ $item->quantity * $item->price}}</td>
{{ $total = $total + ($item->quantity * $item->price) }}
</tr>
#endforeach
<p>Sum: {{ $total }}</p>
</tbody>
You can use blade's #php directive like this
<tbody>
#php
$total = 0
#foreach($items as $items)
<tr>
<td>{{$item>id }}</td>
<td>{{$item->quantity}}</td>
<td>{{$item->price}}</td>
<td>{{$total = $total + ($item->quantity * $item->price)}}</td>
</tr>
#endforeach
<p>Sum: {{ $total }}</p>
#endphp
</tbody>
Try the following:
{{ $sum = 0 }}
<tbody>
#foreach($items as $items)
<tr>
<td>{{$item>id }}</td>
<td>{{$item->quantity}}</td>
<td>{{ $item->price}}</td>
<td>{{ $item->quantity * $item->price}}</td>
</tr>
$sum+ = $item->quantity * $item->price;
#endforeach
<p>Sum: {{ $sum }}</p>
</tbody>
I assume here $items is a Illuminate\Support\Collection. You can calculate a sum using a closure:
$items->sum( function ($item) {
return $item->quantity * $item->price;
});
Or in your blade template:
{{ $items->sum( function ($item) {
return $item->quantity * $item->price;
}); }}
See Laravel Collections docs.

Obtaining field from table using primary key

Using Laravel and Revisionable Package for tracking changes. In my view I'm populating my table:
#foreach($revisions as $revision)
#if($revision->key == 'created_at' && !$revision->old_value)
<tr>
<td>{{ $revision->revisionable_type }}</td>
<td>{{ $revision->revisionable_id }}</td>
<td width="50">{{ $revision->userResponsible()->first_name }}</td>
<td Width="50"></td>
<td></td>
<td>{{ $revision->newValue() }}</td>
<td width="150">{{ $revision->created_at }}</td>
</tr>
#else
<tr>
<td>{{ $revision->revisionable_type }}</td>
<td>{{ $revision->revisionable_id }}</td>
<td width="50">{{ $revision->userResponsible()->first_name }}</td>
<td width="50">{{ $revision->fieldName() }}</td>
<td>{{ $revision->oldValue() }}</td>
<td>{{ $revision->newValue() }}</td>
<td width="150">{{ $revision->updated_at }}</td>
</tr>
#endif
#endforeach
The second column {{ $revision->revisionable_id }} happens to be the primary key of the user record that was modified. I would like to return the email address or first_name/last_name of that users record. I'm fairly new at this and could use a push in the right direction!
Thanks!
You can access the model that given revision relates to by accessing the revisionable relation of that revision. In your case, in order to display the email property of related model, you could do the following:
<td>{{ $revision->revisionable->email }}</td>
from the variable names revisionable_type & revisionable_id I assume you're using many to many Polymorphic relation. based on that
you've to define a relation in the Revision Model with the User like so:
public function users()
{
return $this->morphedByMany('App\User', 'taggable');
}
so you can use all the revisions related to this user $revision->users this will return array
and if you're sure that you've only one record related to this object like your case as I think. you can use $revision->users->first()->email or username, etc..
Laravel Docs

Sum values in foreach loop in [php]

I want to sum tot_Price and unit_Price respectively so that I can analyze the average of these two attributes.
<tr>
<td>{{ $X_land->house_Type }}</td>
<td class="address">{{ $X_land->the_Location }}</td>
<td>{{ $X_land->tot_Price }}</td>
<td>{{ $X_land->tran_Area }}</td>
<td>{{ $X_land->unit_Price }}</td>
<td><button id="opener<?php echo $opencount?>">詳細資訊</button></td>
</tr>
How should I do this?
Thanks.
You could add sum variable for both tot_Price and unit_Price and add in foreach loop
<?php $sum_tot_Price = 0 ?>
<?php $sum_unit_Price = 0 ?>
#foreach ($yourData as X_land)
<tr>
<td>{{ $X_land->house_Type }}</td>
<td class="address">{{ $X_land->the_Location }}</td>
<td>{{ $X_land->tot_Price }}</td>
<td>{{ $X_land->tran_Area }}</td>
<td>{{ $X_land->unit_Price }}</td>
<td><button id="opener<?php echo $opencount?>">詳細資訊</button></td>
</tr>
<?php $sum_tot_Price += $X_land->tot_Price ?>
<?php $sum_unit_Price += $X_land->unit_Price ?>
#endforeach
<tr>
<td>Sum tot_Price {{ $sum_tot_Price}}</td>
<td>Sum unit_Price {{ $sum_unit_Price}}</td>
</tr>
Assume:
#foreach($lands as $X_land)
<tr>
<td>{{ $X_land->house_Type }}</td>
<td class="address">{{ $X_land->the_Location }}</td>
<td>{{ $X_land->tot_Price }}</td>
<td>{{ $X_land->tran_Area }}</td>
<td>{{ $X_land->unit_Price }}</td>
<td><button id="opener<?php echo $opencount?>">詳細資訊</button></td>
</tr>
#endforeach
You can get total like this:
{{$lands->sum('tot_Price')}}
{{$lands->sum('unit_Price')}}
Or you can get average:
{{$lands->avg('tot_Price')}}
{{$lands->avg('unit_Price')}}
To be very simple,
You need to focus on the #foreach loop first,
e.g #foreach($people as $person)
and there is the salary which you can access in foreach,
Through $person->salary
If you want to calculate the sum of salaries then use a simple sum like this,
$people->sum('salary'), Remember not use $person
In your case
{{$lands->sum('tot_Price')}}
{{$lands->sum('unit_Price')}}

Categories