I'm creating an backend with multiple stores. Each stores with their own products
I've created a store and a product and am trying to resource the products to all the stores.
When I try add my products to my store in StoreResource.php
using:
'products' => ProductResource::collection($this->products),
I get the error:
Call to a member function first() on string
I've looked on line for numerous explanations and tutorials, but get met with the same error
* STORE MODEL *
public function products()
{
return $this->hasMany(Product::class);
}
*STORE CONTROLLER *
public function index()
{
return StoreResource::collection(Store::with('products')->paginate(5));
}
STORE Resource
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class StoreResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'description' => $this->description,
'image' => $this->image,
'created_at' => (string) $this->created_at,
'updated_at' => (string) $this->updated_at,
'products' => ProductResource::collection($this->products),
];
}
}
* Product MODEL *
public function stores()
{
return $this->belongsTo(Store::class);
}
*Product CONTROLLER *
public function index()
{
return ProductResource::collection(Product::with('stores')->paginate(5));
}
Product Resource
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class Purchaseresource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'productName' => $this->productName,
'amount' => $this->amount,
'total_product_price' => $this->total_product_price,
'week' => $this->week,
'day' => $this->day,
'month' => $this->month,
'year' => $this->year,
'created_at' => (string) $this->created_at,
'updated_at' => (string) $this->updated_at,
];
}
}
What I expect is to get a relation between my store and products so they are displayed as this in the API repsonse
{
"id": 0,
"name": "Store",
"image": "image",
"products": [
{
"id": 1,
"name": "product",
"price": 7,
"qty": 100,
"total": 0
},
]
}
So the product would become nested in the store.
from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2HDetyP
via IFTTT
Aucun commentaire:
Enregistrer un commentaire