I'm working on a Laravel project and I want to create a REST API for a website. On my system, I have two tables: my tables are Item and Product table which both have one to one relationship i want the json response from two tables like below
"data": [
{
"product_id": 3,
"product_name": "xyz",
"sold": 0,
"total": 500
}
}
]
but the actual format am getting is like below
"data": [
{
"product_id": 3,
"product_name": "xyz",
"prod": {
"id": 1,
"products_id": 3,
"sold": 0,
"total": 500
}
}
]
My Item Controller class
class ItemCont extends BaseController
{
public function index()
{
$items= Items::all();
return $this->sendResponse(ItemResource::collection($items), 'Items retrieved successfully.');
}
}
My ItemResource class
class ItemResource extends JsonResource
{
public function toArray($request)
{
return parent::toArray($request);
}
}
Items Model
class Items extends Model
{
public $timestamps = false;
protected $primaryKey = 'product_id';
protected $guarded = [];
protected $fillable = [
'product_name'
];
public function prod(){
return $this->hasOne('App\Products','products_id','product_id');
}
}
products Model
class Products extends Model
{
public $timestamps = false;
protected $primaryKey = 'id';
protected $guarded = [];
protected $fillable = [
'sold','total'
];
public function item(){
return $this->belongsTo('App\Items','product_id','products_id');
}
}
products resource class
class ProductResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return parent::toArray($request);
}
Thanks The second method i Have tried is my ItemResource class
class ItemResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
//return parent::toArray($request);
return [
'Product_id' => $this->id,
'product_name' => $this->name
//'products' => new Products($this->products),
//'sold' => $this->sales,
//'total' => $this->total,
];
}
my Product Resource class
class ProductResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
"sold" => $this->sales,
"total"=>$this->total
];
// return parent::toArray($request);
}
and my ItemController class
class ItemCont extends BaseController
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$items= Items::with('prod')->get();
return $this->sendResponse(ItemResource::collection($items), 'Items retrieved successfully.');
}
Response for second method try is
{
"success": true,
"data": [
{
"Product_id": null,
"product_name": null
},
{
"Product_id": null,
"product_name": null
}
],
"message": "Items retrieved successfully."
}