Jareer
Jareer

Reputation: 252

How to attach two fields in json response array in Laravel

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

enter image description here

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

Answers (3)

jeremykenedy
jeremykenedy

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

Jareer
Jareer

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'];

Result enter image description here

Upvotes: 0

Kamlesh Paul
Kamlesh Paul

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

Related Questions