Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Alewa's avatar
Level 2

Laravel API Error

I have written an api code for product details, and every thing is working perfectly. But the moment i added relatedProducts, I get this error when running my api

ErrorException: Undefined array key "product_category" in file D:\xampp\htdocs\jaano\jaanobackend\vendor\laravel\framework\src\Illuminate\Collections\Collection.php on line 1641

#0 D:\xampp\htdocs\jaano\jaanobackend\vendor\laravel\framework\src\Illuminate\Collections\Collection.php(1641): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(2, 'Undefined array...', 'D:\xampp\htdocs...', 1641)
#1 D:\xampp\htdocs\jaano\jaanobackend\app\Http\Controllers\API\ApiV1ProductController.php(166): Illuminate\Support\Collection->offsetGet('product_categor...')

My ApiV1ProductsController.php code

<?php

namespace App\Http\Controllers\API;

use App\Models\Product;
use App\Models\Brand;
use App\Models\Section;
use App\Models\ProductCategory;
use App\Models\ProductAttribute;
use App\Models\Cart;
use App\Models\Wishlist;
use App\Models\ProductRating;
use App\Models\Order;
use App\Models\OrdersProduct;
use App\Models\DeliveryAddress;
use App\Models\Country;
use App\Models\User;
use Auth;
use DB;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class ApiV1ProductController extends Controller
{
    public function viewProductCategories(){
        $productcategories = Section::with('product_categories')->get();
        return response()->json([
            "status"=>true,
            "productcategories"=>$productcategories
        ],200);
    }

    public function productDetails($id){
        $productCount = Product::where(['id'=>$id,'status'=>1])->count();
        if($productCount > 0){
            $productDetails = Product::with(['section','product_category','brand','product_attributes'=>function($query){
                $query->where('stock','>',0)->where('status',1);
                },'product_images'])->where('id',$id)->get();

            $relatedProducts = Product::where('product_category_id',$productDetails['product_category']['id'])->where('id','!=',$id)->limit(8)->inRandomOrder()->get();

            foreach($productDetails as $key => $value){
                $getDiscountPrice = Product::getDiscountPrice($productDetails[$key]['id']);
                if($getDiscountPrice>0){
                    $productDetails[$key]['final_price'] = "GHC.".$getDiscountPrice;
                }else{
                    $productDetails[$key]['final_price'] = "GHC.".$productDetails[$key]['product_sales_price'];
                }
                $productDetails[$key]['product_image'] = url($productDetails[$key]['product_image']);
            }

            return response()->json([
                "status"=>true,
                "product"=>$productDetails,
                "relatedProducts"=>$relatedProducts
            ],200);
        }else{
            return response()->json([
                "status"=>false,
                "message"=>"Product with this ID not found!"
            ],422);
        }
    }

}

My Product.php model code

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasFactory;

    public function admin_created(){
        return $this->belongsTo('App\Models\Admin', 'admin_created_id');
    }

    public function admin_updated(){
       return $this->belongsTo('App\Models\Admin', 'admin_updated_id');
    }

    public function vendor_created(){
        return $this->belongsTo('App\Models\Admin', 'vendor_created_id');
    }

    public function vendor(){
        return $this->belongsTo('App\Models\Vendor', 'vendor_created_id')->with('vendorbusinessaccounts');
    }

    public function section()
    {
        return $this->belongsTo('App\Models\Section', 'section_id');
    }

    public function product_category()
    {
        return $this->belongsTo('App\Models\ProductCategory', 'product_category_id');
    }

    public function brand()
    {
        return $this->belongsTo('App\Models\Brand', 'brand_id');
    }

    public function product_attributes()
    {
        return $this->hasMany('App\Models\ProductAttribute');
    }

    public function product_images()
    {
        return $this->hasMany('App\Models\ProductImage');
    }

    public static function getDiscountPrice($product_id)
    {
        $proDetails = Product::select('product_sales_price','product_discount','product_category_id')->where('id',$product_id)->first();
        if($proDetails->product_discount > 0){
            //Find product discount from products database table
            $discounted_price = $proDetails->product_sales_price - ($proDetails->product_sales_price * $proDetails->product_discount/100);
        }else{
            $discounted_price = 0;
        }

        return $discounted_price;
    }

    public static function getDiscountAttributePrice($product_id,$size){
        $proAttrPrice = ProductAttribute::where(['product_id'=>$product_id,'size'=>$size])->first()->toArray();
        $proDetails = Product::select('product_discount','product_category_id')->where('id',$product_id)->first();
        $proDetails = json_decode(json_encode($proDetails),true);
        if($proDetails['product_discount'] > 0){
            //Find product discount from products database table
            $final_cost_price = $proAttrPrice['cost_price'];
            $final_price = $proAttrPrice['sales_price'] - ($proAttrPrice['sales_price'] * $proDetails['product_discount']/100);
            $discount = $proAttrPrice['sales_price'] - $final_price;
        }else{
            $final_cost_price = $proAttrPrice['cost_price'];
            $final_price = $proAttrPrice['sales_price'];
            $discount = 0;
        }

        return array('product_sales_price'=>$proAttrPrice['sales_price'],'product_cost_price'=>$proAttrPrice['cost_price'],'final_price'=>$final_price,'final_cost_price'=>$final_cost_price,'discount'=>$discount);
    }

    public static function getProductImage($product_id)
    {
        $getProductImage = Product::select('product_image')->where('id',$product_id)->first()->toArray();
        return $getProductImage['product_image'];
    }

    public static function getProductStatus($product_id)
    {
        $getProductStatus = Product::select('status')->where('id',$product_id)->first();
        return $getProductStatus->status;
    }
}

Any help

0 likes
2 replies
s4muel's avatar

couldn't you just replace $productDetails['product_category']['id'] with $productDetails->product_category_id?

Alewa's avatar
Level 2

@s4muel I can but I want the product_category_id field in products table, to be compared or equal to the id field in product_category table, so am not sure the query you have write is comparing both the products table and product_categories table. I will try it an see the outcome. Thanks

Please or to participate in this conversation.