I am trying to get a Date Count using Carbon. Like 20 days ago created. I want to send data in JSON format API.
I want to send it from the controller. Here is my Controller Code.
use Carbon\Carbon;
public function index()
{
$now = Carbon::now();
$users = User::all('first_name', 'last_name', 'profile_img', 'created_at');
$date = $users->created_at->diffInDays($now);
return response()->json(['data' => $users , 'date' => $date]);
}
But I get the error from the postman
Without the Date count, I can get all data without any error. So My problem is in here just. Please inform me where is I am wrong. Thank You
CodePudding user response:
first of all, you're trying to get data from a collection of objects. it might be pluck or you may use a for each loop here to modify your data. like as -
$date = array();
foreach($users as $user){
$date[] = $user->created_at->diffInDays($now); // or $user->created_at->diffForHumans();
}
for API you may use resource or Laravel Repository Pattern.
CodePudding user response:
I have done it using model accessor laravel. In User
Model I am creating a function
public function getCreatedAtAttribute($created_at)
{
return Carbon::parse($created_at)->diffInDays(now());
}
and In Controller
, I have used this code.
public function index()
{
$users = User::all('first_name', 'last_name', 'profile_img', 'created_at');
return response()->json(['data' => $users], 200);
}
And now IT sends a fine result
Thank's all.
CodePudding user response:
you can also format date in different format like this via model accessor
protected function serializeDate(DateTimeInterface $date)
{
return $date->format('Y-m-d H:i:s');
}