Lumen: I need to display two dates in a single field

Asked

Viewed 23 times

0

I have to return a json that displays a Person object that contains Another Experience object. I’m using hasMany in Model Person and returning Json that way:

$person = $this->model->with('experiences')->find($id);
return response()->json($person, Response::HTTP_OK);

and I get back Json:

{
    "name": "João",
    "last_name": "Antonio",
    "experiences": [
        {
            "date_start": "2019-02-01",
            "date_end": "2019-03-04",
            "description": "Descrição"
        }
    ]
}

I need to return a "date" field that contains the date_start and date_end field in the following format:

{
    "name": "João",
    "last_name": "Antonio",
    "experiences": [
        {
            "date": "February 2019 - March 2019",
            "description": "Descrição"
        }
    ]
}

1 answer

1


You need to format the output directly on SQL of the relationship with the Builder of Eloquent and in the SQL the date_format which opens a range of how to format output a date, example:

$person = $this->model
          ->with(['experiences' => function($query){
              $query->selectRaw(
                'id,
                 description,
                 concat(date_format(date_start,"%M %Y"),"-",date_format(date_end,"%M %Y")) 
                 as date'
              );
           }])
          ->find($id);

where and much notice in that the first item I put the word id more there is the field that relates to the table $person. Example if the table experiences relates to person across the countryside person_id is that name that should be put in place of the id of example like this, the rest stays the way it is.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.