This is about Laravel query. I want get some data from db. I used below code for it,
$ids = [1, 2, 3, 4, 5]
$stock = $item->stocks->whereIn('paperorder_paper_id', $ids)->where('status', 'qc-pass')->get();
When simplified My problem is if id no 1 has a record it should display that value otherwise should display zero ("0"). Because I want to put data in to datable. Please see the image. Then clearly understand what is my problem.
Expected:
Problem and I got the result
stocks DB
Id Value
1
2 120
3 50
4
5 1000
below has my real code in the blade file. But complicated to explain using real code. Please help me solved this thing.
<td class="border-t border-gray-200 border-dashed">
@php
$paperorderids = [];
$paperorder = $item->paperorders->where('paperorder_id', $item->id);
foreach ($paperorder as $key => $value) {
$paperorderids[] = $value->id;
}
// Output: $ids = [1, 2, 3, 4, 5]
$stock = $item->stocks->whereIn('paperorder_papers_id', $paperorderids)->where('status', 'qc-pass');
// Output: 2 arrays only becasue others id has not record thats why I want zero for that.
foreach ($stock as $key => $val) {
echo $val->qty ? $val->qty : 0;
}
//
@endphp
{{-- @foreach ($item->paperorders as $paperorder)
@foreach ($item->stocks as $stock)
@if ($paperorder->id == $stock->paperorder_papers_id && $stock->status === 'qc-pass')
<span class="flex items-center px-6 py-0 text-gray-700">
{{ $stock->qty }}
</span>
@else
<span class="flex items-center px-6 py-0 text-gray-700">
0
</span>
@endif
@endforeach
@endforeach --}}
</td>
CodePudding user response:
That should do it.
echo in_array($val->id, $ids) ? $val->qty : 0;
CodePudding user response:
Thanks for help me here is my final code and it's worked for me.
@php
$stock = $item->stocks->where('status', 'qc-pass');
$stockids = [];
foreach ($stock as $key => $sids) { $stockids[] = $sids->paperorder_papers_id;}
@endphp
@foreach ($item->paperorders as $val)
<span class="flex items-center px-6 py-0 text-gray-700">
@if (in_array($val->id, $stockids))
{{ $item->stocks->where('paperorder_papers_id', $val->id)->where('status', 'qc-pass')->sum('qty'); }}
@else
0
@endif
</span>
@endforeach