1

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,
                     ]
           ]

3 Answers 3

1

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

Comments

0

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

Comments

0

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

2 Comments

And what does dd($this->cards); in ListResource show?
show 4 cards only the data have 8 cards how is that happen?

Your Answer

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