Get total of the column with where condition - php

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

Related

Can't load model data into create() function (ERROR: Call to a member function with() on array)

I get this error when trying to load a table into my create() function so that the user can select from a list of team_names in the create user page: Call to a member function with() on array
Here is my UserController.php
use Illuminate\Http\Request;
use App\Game;
use App\User;
use App\Team;
...
public function create()
{
$pagetitle = 'Create User';
$teams = Team::orderBy('team_name', 'asc')->get();
if(auth()->user()->user_type !== 'admin'){
return redirect('/')->with('error', "You do not have access to the game you attempted to view.");
}
return view('pages.admin.users.create', compact('pagetitle')->with('teams', $teams));
}
Here is my create.blade.php
#if(count($teams) > 0)
#foreach($teams as $team)
<option value="{{$team->id}}">{{$team->team_name}}</option>
#endforeach
#else
<p>No teams found...</p>
#endif
Relationships really should not matter in this case, though I do have all of them properly set up.
For context: I'm creating a "User", but loading all of the "Team" names.
Any help is greatly appreciated.
compact('pagetitle')->with('teams', $teams) is wrong.
compact('pagetitle') returns an array. there is no function called with() on array.
To returns an array contains both pagetitle and teams you can use compact.
compact('pagetitle', 'teams');
That's it.
So,
return view('pages.admin.users.create', compact('pagetitle', 'teams'));
You can use compact() or with() to pass object to view.
return view('pages.admin.users.create',compact('pagetitle','teams'));
OR
return view('pages.admin.users.create')->with('pagetitle',$pagetitle)->with( 'teams',$teams);

Putting query inside a for loop with condition in laravel

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

How to get data using foreign key in eloquent model?

I have model named 'PropertyLead' as,
class PropertyLead extends Model
{
public function leadPropertyDetails()
{
return $this->belongsTo('App\Models\Property\Property', 'Property_id','id');
}
public function user()
{
return $this->belongsTo('App\Models\Access\User\User','user_id','id');
}
public function propertyRatings()
{
return $this
->hasMany('App\Models\Property\PropertyRating','Property_id','Property_id');
}
}
In my controller I am trying to get data as ,
$leads = PropertyLead::with('leadPropertyDetails','user','propertyRatings')
->get();
Here in $leads variable i am getting all the data that I want but In 'propertyRatings' I am getting user_id and other details. I also want to get the name user who rated that property using that user_id in propertyRatings object. I am really troubled in this query. Thanks in advance.
Use nested eager loading syntax to load nested relationships:
PropertyLead::with('propertyRatings', 'propertyRatings.user', 'leadPropertyDetails', 'user')->get();
Then you be able to display user name with:
#foreach ($leads as $lead)
#foreach ($lead->propertyRatings as $propertyRating)
{{ $propertyRatings->user->name }}
#endforeach
#endforeach

Get the amount of the bill in the class method

Sorry for my English.
I want to make a record that would be deduced me the sum of all my orders, that is, folded string of orders and drew grouped by orders.
I have created a model "Sale", which comprises method AmountOrder
public function AmountOrder()
{
$AmountOrder = DB::table('goods')
->join('sale_lines', 'sale_lines.good_id', '=', 'goods.id')
->where('sale_id', $this->id)
->select(DB::raw('SUM(price*quantity) as total_sales'))
->value('total_sales');
return $AmountOrder;
}
and to deduce the code like this
#foreach ($sales as $sale)
<tr>
<td class="table-text"><div>{{ $sale->id }}</div></td>
<td>
{{ $sale->client->name }}
</td>
<td>
{{$sale->date}}
</td>
<td>
{{$sale->AmountOrder($sale)}}
</td>
<td>
{{$sale->debt($sale)}}
</td>
<td>
{{$sale->date_of_issue}}
</td>
</tr>
#endforeach
But the problem is that the query is performed on each line. I'm new to Laravel, but thought maybe you can solve this problem somehow more beautiful?
Thank you very much in advance!
You are probably talking about the Eager Loading.
From the docs:
When accessing Eloquent relationships as properties, the relationship data is "lazy loaded". This means the relationship data is not actually loaded until you first access the property. However, Eloquent can "eager load" relationships at the time you query the parent model. Eager loading alleviates the N + 1 query problem.
However, you will be not able to use the Eager Loading now, with this code in the AmountOrder method.
A simple google search, also, led me to this example of Eager Loading with aggregate functions/relationships.
It will be probably a good start to think and implement your solution.
you have wrong in your select :
$AmountOrder = DB::table('goods')
->join('sale_lines', 'sale_lines.good_id', '=', 'goods.id')
->where('sale_id', $this->id)
->select(DB::raw('SUM(sale_lines.price*sale_lines.quantity) as total_sales'))
->value('total_sales');
My relationship
class Sale extends Model
{
//Получаем товар в этой продаже
public function good()
{
return $this->belongsTo('App\Good');
}
}
class Good extends Model
{
//В каких закупках был этот товар
public function purchases()
{
return $this->hasMany('App\Purchase');
}
//Продажи с этим товаром
public function sales()
{
return $this->hasMany('App\Sale');
}
}
Is it correct?
In my model i create method
public function AmountOrderRelation()
{
return $this->belongsTo('App\Good')
->selectRaw('sum(price) as aggregate, id')
->groupBy('id');
}
In controller
$new_sales = Sale::with('AmountOrderRelation')->get();
#foreach ($new_sales as $sale)
<tr>
<td class="table-text"><div>{{ $sale->id }}</div></td>
<td>
{{ $sale->AmountOrderRelation }}
</td>
</tr>
#endforeach
But my relations is null. What's my mistake?
I did it!
public function AmountOrder()
{
return $this->HasOne('App\SaleLines')
->join('goods', 'sale_lines.good_id', '=', 'goods.id')
->selectRaw(DB::raw('SUM(price*quantity) as aggregate, sale_id'))
->groupBy('sale_id');
}
public function getAmountOrderAttribute()
{
// if relation is not loaded already, let's do it first
if ( ! array_key_exists('AmountOrder', $this->relations))
$this->load('AmountOrder');
$related = $this->getRelation('AmountOrder');
// then return the count directly
return ($related) ? (int) $related->aggregate : 0;
}
And in controller
$sales = Sale::with('AmountOrder')->get();

data in included views in laravel

In my laravel app, I am passing a variable $data to a view which I will later include in another view. So in my controller method, I have:
public function random($id){
$data = DB::table('reports')->where('id',$id);
return view('partials.data', compact('data'));
}
In the partials.data I have:
{!! Form::open(['url'=>'reports/data',$id]) !!}
<table class="table table-responsive table-condensed table-bordered tab-content">
<thead>
<tr>
<th>Month</th>
<th>Value</th>
</tr>
</thead>
<tbody>
#foreach($data as $dat)
<tr>{{$dat->month}}</tr>
<tr>{{$dat->value}}</tr>
#endforeach
</tbody>
</table>
{!! Form::close() !!}
And in the main view I have this function:
function kpi_values(d) {
// `d` is the original data object for the row
kpi = d.id;
return '#include("reports.data", array("id" => "kpi"))';
}
Which is triggered by:
$('#monthly_table tbody').on('click', 'td.details-controls', function () {
var tr = $(this).closest('tr');
var row = table.row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
row.child(kpi_values(row.data())).show();
tr.addClass('shown');
}
});
When I run this I get the following error:
ErrorException in 3534c4c98c65c2d5267bf7c54a960d41 line 13:
Undefined variable: data
I have passed the variable data in my partial view, however, it seems like it requires it in the primary view.
Is there any way of doing this without passing the variable to the primary view? I don't want to mix things because the partial view controller method requires a parameter, while the primary view has no parameters in it.
Laravel offers a great tool to handle this situation in which we need to pass some parameters to partial views without passing through the primary view. That is view composer. Here is an example :
In \App\Providers\AppServiceProvider.php file
public function boot()
{
//get data and pass it to partials.data whenever partials.data is executed
view()->composer('partials.data',function($view){
$view->with('data',DataSet::all());
});
}
For more advanced, you can learn it from Laracast
You may use share methods to pass the data to all views.
return view('partials.data')->share('data', $data);

Categories