Reputation: 252
I need to attach the start_date
and start_time
into one field in the response as start
= start_date
+ start_time
in the json array, this is how i get display the json array
I need to show as start
: "2021-02-18 12:32:00" with all the other fields too
Here's my controller function
public function calendar(Job $job)
{
$user = auth()->user();
$calendar= $job->where('user_id',$user->id)->get();
return response()->json($calendar);
}
Upvotes: 0
Views: 303
Reputation: 4285
In your Job model you can use the $append
and create and attribute for it then it will always be part of the results with the model:
class Job extends Model
...
/**
* The accessors to append to the model's array form.
*
* @var array
*/
protected $appends = [
'start',
];
...
public function getStartAttribute()
{
return $this->start_date . $this->start_time;
}
...
Upvotes: 0
Reputation: 252
I was able to fix the above problem finally by adding the below codes
Controller function
public function calendar(Job $job)
{
$user = auth()->user();
$calendar = $job->where('user_id',$user->id)->get();
$calendar = $calendar->map(function ($post) {
$post['start'] = $post->start_date . ' ' . $post->start_time;
$post['end'] = $post->end_date . ' ' . $post->end_time;
// unset($post['name']);
return $post;
});
return response()->json($calendar);
}
Model
protected $visible = ['start','end'];
Upvotes: 0
Reputation: 12391
you can use map() function to loop over and can add new key like this
public function calendar(Job $job)
{
$user = auth()->user();
$calendar = $job->where('user_id', $user->id)->get();
$calendar->map(function($row){
return $row->start = $row->start_date . ' ' . $row->start_time;
});
return response()->json($calendar);
}
Upvotes: 1