user8183017
user8183017

Reputation:

Create nested API

I'm trying to make an api that have lists and inside each list there is anther list inside of it called cards and the cards list is the cards of this list.

I tried to show it in index function and didn't work it was like this:

  public function index()
  { 
   // $list = List -> cards();
    $list = List::cards();

    return response( $list );
  }

Card Model:

  public function list()
   {
        return $this->belongsTo( List::class() );
   }

Card Model:

  public function cards()
   {
        return $this->hasMany( Card::class() );
   }

What i want to output is json data like this:

  "lists":[
           'name':listname

             'cards':[
                       'card one': card name,
                     ]
           ]

Upvotes: 1

Views: 311

Answers (3)

marv255
marv255

Reputation: 818

You can use resources.

Http\Resources\List:

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class List extends JsonResource
{
    public function toArray($request)
    {
        $cards = [];
        foreach ($this->cards as $card) {
            $cards[] = $card->name;
        }

        return [
            'name' => $this->name,
            'cards' => $cards,
        ];
    }
}

Http\Controllers\ListController:

namespacce App\Http\Controllers;

use App\Http\Resources\List as ListResource;
use App\Components\List;

class ListController extends Controller
{
    $lists = List::query()->get();

    return ListResource::collection($lists)->response();
}

Upvotes: 0

Mohammad Habibinodeh
Mohammad Habibinodeh

Reputation: 186

If you use Laravel framework use Resource for response, in Resource of laravel you can load cards. For example in ListController :

public function index()
{
    return ListResource::collection(List::all()->paginate());
}

And in ListResource :

public function toArray($request)
{
    'cards' => CardResource::collection('cards');
}

Upvotes: 1

Vitalii
Vitalii

Reputation: 1175

belongsTo or hasMany accepts model name as a first argument. In your case you need to pass your model class name in your relations methods.

public function list()
{
    return $this->belongsTo(List::class);
}

and

public function cards()
{
    return $this->hasMany(Card::class);
}

So if you want to receive models including relations you can use with method.

return response(List::query()->with('cards'));

Upvotes: 0

Related Questions