Laravel join sum query fetch error double sums - laravel

I got the two following tables:
table name: formulario id primary bigint(20) mes_ano varchar(255) matricula varchar(255)
table name: reparacoes id primary bigint(11) matricula varchar(255) valor varchar(255)
What I want to accomplish is joining on the valor with formulario's values and fetch the data in Laravel view dashboard. I tried the following way, but with the join it doesn't show accurate values.
public function index(Request $request, Formulario $id, Reparacoes $valor)
{
$data = Reparacoes::select(DB::raw("SUM(reparacoes.valor) as sum"))
->join('formulario', 'reparacoes.matricula', '=', 'formulario.matricula')
->orderBy("reparacoes.matricula")
->groupBy(DB::raw("reparacoes.matricula"))
->get();
return view('admin.page', ['data' => $data]);
}
<tbody>
#foreach ($data as $item)
<tr>
<td>{{ $item->matricula }}</td>
<td>{{ $item->sum }}</td>
<td>{{ $item->mes_ano }}</td>
</tr>
#endforeach
</tbody>
I don't even put on the select the mes_ano because the sum it's not working I got two repairs on one matricula that summing up gives 30 in value, and the other matricula that have reparacao has just one of 10 when I apply the join in controller, it shows up as the first matricula having a sum of 420. Thanks for whoever helps me doing this join query sum.

Related

Value correlation from multiple tables in laravel

I have two tables. One employees and one timesheets
I would like to have correct name at the result but different ID. If you see the result I have the same name everywhere.
How can make the code to fixed my challenge?
Thank you.
In controller I have this code
$profile = ['no' => Auth::user()->no];
$timesheets = Timesheet::where($profile)->select('*')->orderBy('created_at','DESC')->get();
foreach ($timesheets as $employee) {
$emp = ['identification' => $employee->identification];
$oneemployee = Employees::where($emp)->select('*')->orderBy('created_at','DESC')->get();
}
return view('contractor.employees.timesheets', compact('timesheets', 'oneemployee'));
and in blade I have
#foreach ($timesheets as $row1)
<tr>
<td>#</td>
#foreach ($oneemployee as $row2)
<td>{{ $row2->fname}}</td>
<td>{{ $row2->lname}}</td>
#endforeach
<td>{{ $row1->identification}}</td>
<td>{{ $row1->week}}</td>
<td>{{ $row1->year}}</td>
</tr>
#endforeach
According to your commit, I suggest the following solution
If you want dispay timesheet with employees you can use eager loading.
For example:
In your controller:
$profile = ['no' => Auth::user()->no];
$timesheets = Timesheet::where($profile)->with("employees")->select('*')->orderBy('created_at','DESC')->get();
return view('contractor.employees.timesheets', compact('timesheets'));
In your Timesheet model add hasOne relation to Employee:
public function employee(){
return $this->hasOne(Employee::class,'identification','identification')
}
And your view:
#foreach ($timesheets as $timesheet)
<tr>
<td>#</td>
<td>{{ $timesheet->employee->fname}}</td>
<td>{{ $timesheet->employee->lname}}</td>
<td>{{ $timesheet->identification}}</td>
<td>{{ $timesheet->week}}</td>
<td>{{ $timesheet->year}}</td>
</tr>
#endforeach

Laravel 7: Match two column dates with current date and show value depends on the condition

Leave:
id
user_id
start_date
end_date
1
2
2022-06-01
2022-06-03
Blade:
#foreach ($users as $row )
<tr>
<td>{{ $loop->iteration }}</td>
<td>{{ $row->id }}</td>
<td>{{ $row->name }}</td>
<td>{{ $row->dpt->department }}</td>
#php
$today = Carbon\Carbon::now();
$leave = App\Leave::where('user_id', $row->id)->whereBetween('') <!-- incomplete -->
#endphp
<td>Leave Status</td>
</tr>
#endforeach
In this table, all user lists are shown. Here in the Leave Status column, it will show On Leave if the user is on leave today. I think I have to match today's date with start_date and end_date of the leave table and also match the user_id
What will be the eloquent query for this?
Example:
id
name
Leave Status
1
Jhon
Present
2
Doe
On Leave
3
Laura
On Leave
If you also have the relationships defined in the model you could load them with constraints in your controller:
$users = User::with(['leaves' => function ($query) {
$query->where('start_date', '>=', Carbon::now()))
->where('end_date', '<=', Carbon::now()));
}])->get();
This way you don't have to query in your blade templates and you can just check if count($row->leaves) > 0
have you try this:
\Carbon\Carbon::now()->between($row->leaves()->last()->start_date,$row->leaves()->last()->end_date) ? 'On Leave' : 'Present';

Foreach inside Foreach based on column value

I have an sql table knowledgebase like so
id , categoryid, title
id
categoryid
title
1
1
apple
2
1
fb
3
2
google
4
2
DB
5
3
Reebok
In my laravel blade, I am trying to create a tree view to look like the following
-1
--apple
--FB
-2
--google
--DB
-3
--Reebok
My controller does a basic query and returns the entire table to the view. I am a newbie to laravel so far, I can get a basic table to work like
#foreach($knowledgebase as $key => $value)
<tr>
<td>{!! $knowledgebase ->id !!}</td>
<td>{!! $knowledgebase ->title!!}</td>
<td>{!! $knowledgebase ->categoryid !!}</td>
</tr>
#endforeach
How would I iterate categroyid column , display first category and all child titles and then move on to the next categoryid.
Update
public function show($id) {
//get article
$knowledgebase = \App\Models\Knowledgebase::Where('knowledgebase_slug', request('knowledgebase_slug'))->first();
return view('knowledgebase', compact('knowledgebase'));
}
You will need to retrieve in controller the categories before ($categories)
#foreach($categories as $category)
<tr>
<td>{{ $category->id }}</td>
<td>{{ $category->title}}</td>
<td>{{ $category->categoryid }}</td>
</tr>
#endforeach
Anyways, I managed to solve this by adding a function children in my model. So in my Model added
public function children(){
return $this->hasMany('App\Models\Knowledgebase', 'categoryid');
}
After this, I simply called it as a foreach inside my foreach
#foreach($categories as $category)
<li>{{ $category->title}}</li>
#if($category->children)
#foreach($category->children as $child)
<ul>
<li class="pl-3"> {{ $child->title}} </li>
</ul>
#endforeach
#endif
#endforeach

Laravel Aggregates query not working according to group by

On POS when I place any order it stored the order detail according to the product id on order_details table. I want to sum the quantity order according to product id.
Order Detail table : id, order_id, product_id, total, created_at, updated_at
Product Controller :
public function index()
{
$orderdetail = DB::table('order_details')
->select('quantity', DB::raw('sum(quantity) as sum'))
->groupBy('product_id')
->havingRaw('SUM(quantity)')
->get();
$products = Product::latest()->with('category', 'supplier', 'orderdetail')->get();
return view('admin.product.index', compact('products', 'orderdetail'));
}
On Product Model:
class Product extends Model
{
protected $dates = [
'buying_date', 'expire_date',
];
public function category()
{
return $this->belongsTo(Category::class);
}
public function supplier()
{
return $this->belongsTo(Supplier::class);
}
public function orderdetail()
{
return $this->belongsTo('App\OrderDetail', 'id', 'product_id');
}
}
}
But it does not show anything on Blade.
on Blade :
#foreach($products as $key => $product)
<tr>
<td>{{ $key + 1 }}</td>
<td>{{ $product->name }}</td>
<td>
<img class="img-rounded" style="height:35px; width: 35px;" src="{{ URL::asset("storage/product/".$product->image) }}" alt="{{ $product->name }}">
</td>
<td>{{ $product->category->name }}</td>
<td>{{ $product->supplier->name }}</td>
<td>{{ $product->code }}</td>
<td>{{ $product->buying_date->toFormattedDateString() }}</td>
<td>{{ number_format($product->buying_price, 2) }}</td>
<td>{{ number_format($product->selling_price, 2) }}</td>
<td>{{ $product->product_unit }}</td>
<td>{{ $product->product_unit - $product->sum }}</td>
<td>{{ $product->sum }}</td>
<td>DLT</td>
</tr>
#endforeach
This is the result of dd on $products and $orderdetail
It aggregates the value not showing the blade template. how I show it on the blade or there any problem on model or blade? please help.
Here I solved via this way
on Controller
public function index()
{
$orderdetail = DB::table('order_details')
->select('quantity', DB::raw('sum(quantity) as soldunit'))
->groupBy('product_id')
->get();
$products = Product::latest()->with('category', 'supplier', 'orderdetail')->get();
return view('admin.product.index', compact('products', 'orderdetail'));
}
and on Model, I have slightly Changed
public function orderdetail()
{
return $this->hasMany('App\OrderDetail','product_id', 'id')->selectRaw('order_details.*,sum(quantity) as soldunit')->groupBy('product_id');
}
after this, to access soldunit on the blade I used this one
{{ $product->orderdetail->sum('soldunit') }}
If you want to access sum of a column via a defined relationship, you need to add it during your main query:
$products = Product::with('category', 'supplier')->with(['orderdetail' => function($query){
$query->select('id', 'product_id', 'quantity', DB::raw('sum(quantity) as sum'));
}])->get();

Laravel need data from two different collections in for each

I have a for each loop to iterate over the collection of records. It has the user_id, but not the other user credentials. I created another collection of user. How do I include this in my iteration?
Controller
public function index(Request $request, $id)
{
$thoughts = Thought::where('id', $id)->orderBy('created_at', 'desc')->paginate(100)->get();
$user = User::where('id', $thoughts->user_id);
return view('backend.pages.thought_list', compact('thoughts, user'));
}
View
#foreach ($thoughts as $thought)
<tr>
<td class="col-md-1">{{ $user->username}} <span class="user_id_thought">ID - {{ $user->user_id}}</span></td>
<td class="col-md-1">{{ $thought->response }}</td>
<td>{{ $thought->thought_type }}</td>
<td>{{ $thought->id }}</td>
</tr>
#endforeach
How do I display my users variable in the loop. Or is there a better way of doing this.
Eager Loading is the perfect use case for your requirement in my opinion.
e.g.
$thoughts = Thought::with('user')->get();
foreach ($thoughts as $thought) {
echo $thought->user->name;
}
For more details see: https://laravel.com/docs/5.6/eloquent-relationships#eager-loading

Resources