I have a products and Ppurchases (stock details) two different tables in my database and using the following controller to fetch stock list.
public function stockapi($id)
{
$data = Ppurchase::where('product_id',$id)->get();
$json_data = json_encode($data);
$data = view('inventory::api.productapi', compact('json_data'));
return response($data)->header("Content-Type","application/json; charset=utf-8");
}
I am getting following JSON:
[
{
"id": 54,
"product_id": 1,
"purchase_id": 45,
"batch": "32",
"manufacture_date": "2017-10-16",
"expiry_date": "2017-10-16",
"quantity": 32,
"invoice_price": 32,
"selling_price": 3,
"product_discount": 32,
"created_at": "2017-10-24 05:31:48",
"updated_at": "2017-10-24 05:31:48"
},
{
"id": 56,
"product_id": 1,
"purchase_id": 46,
"batch": "33",
"manufacture_date": "2017-10-23",
"expiry_date": "2017-10-25",
"quantity": 32,
"invoice_price": 23,
"selling_price": 23,
"product_discount": 23,
"created_at": "2017-10-24 07:46:55",
"updated_at": "2017-10-24 07:46:55"
},
{
"id": 57,
"product_id": 1,
"purchase_id": 47,
"batch": "df",
"manufacture_date": "2017-10-10",
"expiry_date": "2017-10-03",
"quantity": 100,
"invoice_price": 100,
"selling_price": 100,
"product_discount": 100,
"created_at": "2017-10-24 11:58:27",
"updated_at": "2017-10-24 11:58:27"
}
]
Now my problem starts here,
1) How to display these expiry_date and manufacture_date on a human-readable format?
2) How to fetch a product's batch which has fewest day's remaining for expiry? (in addition)
Displaying expiry_date and manufacture_date as a human readable format you can write an Accessor.
You can also use an Accessor for introducing new attribute to find the fewest day's remaining for expiry
I suppose you have model like this then
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
class Ppurchase extends Model
{
public function getExpiryDateAttribute($value)
{
return Carbon::parse($value)->diffForHumans();
}
public function getManufactureDateAttribute($value)
{
return Carbon::parse($value)->diffForHumans();
}
public function getRemainingDaysAttribute()
{
return Carbon::parse($this->expiry_date)->diffForHumans(Carbon::parse($this->manufacture_date));
}
}
Using this you will get the dates in human readable format and you will get a new attribute remaining_days which you can leverage to filter the collection as you want
For more info I recommand you to read this. https://laravel.com/docs/5.5/eloquent-mutators#defining-an-accessor
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With