Skip to content
Advertisement

Return custom array in json model with Lumen

With Lumen 8 I have :

  • Model : Store
  • Controller : StoreController
  • Repository : StoreRepository

I can get my Store without any problem and get the json below :

{
    "id_store": 1,
    "name": "Abcde",
    "email": "",
    "phone": "0123456789"
}

I would like to get open/close time of the Store. In my model I have a array (for test) and I can show it like that :

return response()->json(['item' => $store, 'time' => $store->getTime()], 200);

And get this result :

{
    "item": {
        "id_store": 1,
        "name": "Abcde",
        "email": "",
        "phone": "0123456789"
    },
    "time": {
        "1": "January",
        "2": "February",
        "3": "March"
    }
}

The problem is that I have 2 sections now. How I can have this array inside my store value ? like below :

{
    "id_store": 1,
    "name": "Abcde",
    "email": "",
    "phone": "0123456789"
    "time": {
        "1": "January",
        "2": "February",
        "3": "March"
    }
}

Advertisement

Answer

Missreaded, in Laravel, you can use Resources API Resources, I guess in Lumen no, more docs here: https://laravel.com/docs/8.x/eloquent-resources

And in your resource, just have something like:

public function toArray($request)
{
    return [
        'id_store' => $this->id_store,
        'name' => $this->name,
        'email' => $this->email,
        'phone' => $this->phone,
        'time' => $this->->getTime(),
    ];
}

Or just return something like this:

$store->time = $store->getTime();
return response()->json($store, 404);

Why 404 btw?

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement