0

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);

}

3 Answers 3

1

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);
}
Sign up to request clarification or add additional context in comments.

8 Comments

This didn't work ;( i got the same response json array as before without any errors
Now the response attaches the start_date and end_date this is how it shows [ "2021-02-18 12:32:00", "2021-02-18 07:32:00", "2021-03-01 11:44:00" ] but i need to show as start : "2021-02-18 12:32:00" with all the other fields
still i get the same [ "2021-02-18 12:32:00", "2021-02-18 07:32:00", "2021-03-01 11:44:00" ] ;(
@Jareer i have tested this and it works as expected may be your doing somthing wrong
Sorry @Kamlesh it your codes worked, the issue was in the model I had to add protected $visible = ['start']; in the Job model and it worked, Thanks a lot man !
|
0

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

Comments

0

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;
    }

    ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.