[英]I need to show all user's data with how many days ago they inserted it into the database?
I am trying to get a Date Count using Carbon.我正在尝试使用 Carbon 获取日期计数。 Like 20 days ago created.
就像 20 天前创建的一样。 I want to send data in JSON format API.
我想以 JSON 格式 API 发送数据。
I want to send it from the controller.我想从 controller 发送它。 Here is my Controller Code.
这是我的 Controller 代码。
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但我从 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
谢谢你
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.
它可能是采摘的,或者您可以在此处使用 for each 循环来修改您的数据。 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.对于 API,您可以使用资源或 Laravel 存储库模式。
I have done it using model accessor laravel.我已经使用model 存取器laravel 完成了它。 In
User
Model I am creating a function在
User
Model 我正在创建一个 function
public function getCreatedAtAttribute($created_at)
{
return Carbon::parse($created_at)->diffInDays(now());
}
and In Controller
, I have used this code.在
Controller
中,我使用了此代码。
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现在 IT 发送了一个很好的结果
Thank's all.谢谢大家。
you can also format date in different format like this via model accessor您还可以通过 model 访问器将日期格式化为不同的格式
protected function serializeDate(DateTimeInterface $date)
{
return $date->format('Y-m-d H:i:s');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.