John Davidson

php - I want to get value or zero for display if id has a record in Laravel?

0 comments
Message:


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>


My Answer:
You can achieve this by using the `pluck` method to get an array of quantities for each paper order id, and then checking if the array has a value for each id. If it does, display the quantity, otherwise display 0.

Here's how you can modify your code:

php

@php
$paperorderids = $item->paperorders->pluck('id')->toArray();

$stock = $item->stocks->whereIn('paperorder_papers_id', $paperorderids)->where('status', 'qc-pass')->pluck('qty', 'paperorder_papers_id')->toArray();

foreach ($paperorderids as $id) {
echo isset($stock[$id]) ? $stock[$id] : 0;
}
@endphp



This code will check if the `$stock` array has a value for each paper order id. If it does, it will display the quantity, otherwise it will display 0.

Rate this post

5 of 5 based on 6792 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us