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

stephen waweru's avatar

Call to a member function where() on null error in laravel

i have a system whereby on a user selects the company from which they prefer to buy from.on selecting the company,a page should show all the products in which the company sells and not all the products from the products table.i have been able to achieve that but on selecting the company the page shows all the products from the products table rather than only the products the selected company .i have used a pivot table to link the company with the product it sells.how can I show only the products from a specific company only?here is my function which shows the products.upon adding "find($company_id)" instead of "->get();" i get an error "Call to a member function where() on null error in laravel"

public function showDocumentSupplierView($company_id)
   {
	$merchant_id = $company_id;

	Log::debug('**** showDocumentSupplierView() ****');
	Log::debug('company_id='.$company_id);

    $user_data = new UserData();

	Log::debug('company_id='.$company_id);

    $productids= DB::table('merchantproduct')->
		where('merchant_id',$company_id)->
		pluck('product_id');

    $ids = merchantproduct::where('merchant_id',
        $user_data->company_id())->pluck('product_id');

	$collection = collect($productids);

	$merged = $collection->merge($ids);

	$ids=$merged->all();
    
    $inventory_data = product::whereIn('ptype',
            // added hydrogen here on this list
        ['inventory', 'rawmaterial', 'warranty', 'oilgas','hydrogen'])->
    whereNotNull('name')->whereIn('id', $ids)->find($company_id);


    $company_detail = \App\Models\Company::where('id',
        $merchant_id)->first();

    $my_company_detail = \App\Models\Company::find($user_data->company_id());

    $issuer_merchant_id = $my_company_detail->id;

    $currency = \App\Models\Currency::where('id',
        $my_company_detail->currency_id)->first();

    if (empty($currency)) {
        $currency = \App\Models\Currency::where('code', "MYR")->first();
    }

    $merchantlinkrelation = DB::table('merchantlinkrelation')->
    join('merchantlink', 'merchantlink.id', '=', 'merchantlinkrelation.merchantlink_id')->
    where([
        'merchantlink.initiator_user_id' => $my_company_detail->owner_user_id,
        'merchantlink.responder_user_id' => $company_detail->owner_user_id,
    ])->
    orWhere([
        'merchantlink.responder_user_id' => $my_company_detail->owner_user_id,
        'merchantlink.initiator_user_id' => $company_detail->owner_user_id,
    ])->
    where([
        'merchantlinkrelation.ptype' => 'dealer',
        'merchantlinkrelation.company_id' => $my_company_detail->id
    ])->
    orderBy('merchantlinkrelation.created_at', 'desc')->
    first();

    $warranty_prd_ids = product::whereIn('ptype',
        ['warranty'])->
    whereNotNull('name')->
    whereIn('id', $ids)->pluck('id');

    $pro_prd_ids = product::whereIn('ptype',
        ['customization'])->
    whereNotNull('name')->
    whereNotNull('prdcategory_id')->
    whereIn('id', $ids)->pluck('id');

    $pro_inventory_ids = product::whereIn('ptype',
        ['inventory'])->
    whereNotNull('name')->
    whereNotNull('photo_1')->
    whereNotNull('prdcategory_id')->
    whereNotNull('prdsubcategory_id')->
    whereNotNull('prdprdcategory_id')->
    whereIn('id', $ids)->pluck('id');
    // followed prices from wholesales
    $inventory_idx = product::whereIn('ptype',
        ['inventory'])->
    whereNotNull('name')->
    whereIn('id', $ids)->pluck('id');

    $warranty_price = warranty::
    whereNull('deleted_at')->
    whereIn('product_id', $warranty_prd_ids)->pluck('price', 'product_id');

    // followed prices from pro service
    $proservice_price = prd_proservices::
    whereNull('deleted_at')->
    whereIn('product_id', $pro_prd_ids)->pluck('price', 'product_id');

    // followed prices from inventory
    $inventory_price = prd_inventory::
    whereNull('deleted_at')->
    whereIn('product_id', $pro_inventory_ids)->pluck('price', 'product_id');
    foreach ($warranty_price as $key => $value) {
        $in_float = $value / 100;
        // $warranty_price[$key] = is_int($in_float) ? $in_float.'.00' : $in_float;
        $warranty_price[$key] = $in_float;
    }


    foreach ($proservice_price as $key => $value) {
        $in_float = $value / 100;
        // $warranty_price[$key] = is_int($in_float) ? $in_float.'.00' : $in_float;
        $proservice_price[$key] = number_format($in_float, 2);
    }

    /*
            foreach ($inventory_data as $key => $value) {
                # code...
                if($value->ptype =='inventory'){
                    if( empty($inventory_price[$value->id])){
                     unset($inventory_data[$key]);

                    }
                }
                else if($value->ptype =='warranty'){
                    if( empty($warranty_price[$value->id])){
                     unset($inventory_data[$key]);

                    }
                }
                else if($value->ptype =='customization'){
                    if( empty($proservice_price[$value->id])){
                     unset($inventory_data[$key]);

                    }
                }
            }
     */
    $wholesale_prices = new Wholesale();
    $product_whole_sale_price_and_range = [];

    foreach ($inventory_idx as $key => $value) {
        $wholesale = $wholesale_prices->where('product_id', $value)->get()->toArray();

        if (count($wholesale) !== 0) {
            $price_in_float = $wholesale[0]['price'] / 100;
            $per_item_whole_sale_price = $price_in_float;  /// $wholesale[0]['unit']
            $wholesale[0]['per_item_whole_sale_price'] = number_format($per_item_whole_sale_price, 2);
        } else {
            $wholesale[0]['per_item_whole_sale_price'] = "0.00";
            $wholesale[0]['price'] = "0.00";
        }


        $product_whole_sale_price_and_range[$value] = $wholesale;
    }


    $fuel_ids = $inventory_data->where('ptype', 'oilgas')->pluck('id')->toArray();
    
    $product_oil_gas_price = [];

    
    foreach ($fuel_ids as $f) {

        $ogFuelPrice = DB::table('prd_ogfuel')->where('product_id', $f)->first()->wholesale_price ?? 0;
        // dd($ogFuelPrice);
        /*
        DB::table('og_fuelprice')->join('prd_ogfuel','prd_ogfuel.id',
            '=','og_fuelprice.ogfuel_id')->
        whereDate('og_fuelprice.start' , '<=',\Carbon\Carbon::today())->
        orderBy('og_fuelprice.start', 'desc')->
        where('prd_ogfuel.product_id', $f)->
        select("og_fuelprice.*")->
        first()->price ?? 0;*/

        $product_oil_gas_price[$f] = number_format($ogFuelPrice / 100, 2);
    }

    

    $ids = merchantlocation::where('merchant_id', $issuer_merchant_id)->pluck('location_id');
    $location = location::where([['branch', '!=', 'null']])->whereIn('id', $ids)->latest()->get();

    return view('data.documentsupplier', compact(
        'inventory_data', 'merchant_id', 'company_detail',
        'my_company_detail', 'product_whole_sale_price_and_range', 'wholesale_prices',
        'currency', 'issuer_merchant_id',
        'warranty_price',
        //  'product_oil_gas_price',
        'proservice_price',
        'location', 'merchantlinkrelation'
    ));
  }
0 likes
33 replies
tykus's avatar

What line is giving the error (according to the stack trace)?

stephen waweru's avatar

@tykus the error occurs in this line

$fuel_ids = $inventory_data->where('ptype', 'oilgas','hydrogen')->pluck('id')->toArray();

stephen waweru's avatar

@tykus its in this showDocumentSupplierView($company_id) function but i didnt include it in the code coz my code was working when using ->get() because it showed all the data from the table but when i used ->find($company_id) to get data from this specific company id that's when i got this error

tykus's avatar

@stephen waweru don't you think it would be useful to share the relevant code?

Anyway, $inventory_data obviously is null

Question is... why do you use a Collection method (where) when the result of find is either null or a Model instance???

Sinnbeck's avatar

@stephen waweru Show the exact lines that are causing the error. And add ``` on the line before and after to format it properly

stephen waweru's avatar

@tykus how can i fix it to get the products for each company instead of getting data for all the companies

tykus's avatar

@stephen waweru

but when i used ->find($company_id) to get data from this specific company id that's when i got this error

Where is ->find($company_id) in the code above????

tykus's avatar

@stephen waweru this query seems wrong; you are trying to find one product instance using a Company id????

$inventory_data = product::whereIn('ptype', ['inventory', 'rawmaterial', 'warranty', 'oilgas','hydrogen'])
    ->whereNotNull('name')
    ->whereIn('id', $ids)
    ->find($company_id);

As I mentioned before $inventory_data is null - probably because the $company_id is incorrectly being used to find one product instance!!! If you dd($inventory_data) immediately after that query; you will very likely see that the result is null.

stephen waweru's avatar

@tykus yes i found out as null..i want to get data for that company,,how can i modify the code

tykus's avatar

@stephen waweru what is the relationship between product and company?

stephen waweru's avatar

@tykus i have a included a pivot table that links the 2...here is the relationship in the company(merchant) model

class Merchant extends Model

{ protected $table = 'merchant'; protected $guarded = []; use SoftDeletes;

public function franchises(){
    return $this->belongsToMany(Franchise::class, 'franchisemerchant', 'franchisee_merchant_id', 'franchisee_merchant_id');
}

public function franchisemerchant(){
    return $this->hasMany(FranchiseMerchant::class, 'franchisee_merchant_id');
}

function products(){
    return $this->hasMany('App\Models\product'); 
}

}

stephen waweru's avatar

@tykus i have changed the query to this in the function but still i get all the data from the table.the merchant products is a function i added in the products table which gets data from the merchadiseproducts table..is there any other way i can get data for a single merchant only instead of all the others.

public function merchantproducts(){ return $this->hasMany(merchantproduct::class, 'product_id', 'id'); }

''$inventory_data = product:: whereIn('ptype', ['inventory', 'rawmaterial', 'warranty', 'oilgas','hydrogen'])-> whereNotNull('name')->whereIn('id', $ids)->with('merchantproducts')->get();''

tykus's avatar

@stephen waweru

  1. what is the name of the belongs to many relationship on the product class to associate the product with the Company?
  2. What variable/value do you have to identify the company in the method above?
stephen waweru's avatar

@tykus this is the function that links the relationship in the merchant model

    function products(){
    return $this->belongsToMany('App\Models\product'); 
}

the function doesn't have a code to identify the company..but i have made a variable to get the data from the pivot table for each company

      $getdatafromproduct = DB::table('merchantproduct')->where('merchant_id',$company_id)->get();

..how can i get data using the function above for each company

tykus's avatar

@stephen waweru 🤷‍♂️ I asked you for the other side of that relationship.

How can you possibly identify the merchant whose products you need?

stephen waweru's avatar

@tykus i am using this relationship in the product model

   public function merchantproducts(){
    return $this->hasMany(merchantproduct::class, 'product_id');
}
tykus's avatar
tykus
Best Answer
Level 104

@stephen waweru suppose you have a conventional merchants relationship defined on the product Model, and products relation on the merchant Model:

// Product
public function merchants()
{
    return $this->belongsToMany(merchant::class, 'merchantproduct');
}
// Merchant
public function products()
{
    return $this->belongsToMany(product::class, 'merchantproduct');
}

Now there are two ways you could get the products:

$inventory_data = product::whereIn('ptype', ['inventory', 'rawmaterial', 'warranty', 'oilgas','hydrogen'])
    ->whereNotNull('name')
    ->whereIn('id', $ids)
    ->whereHas('merchants', fn ($builder) => $builder->where('id', $company_id))
    ->get();

Or, if you have a merchant instance:

$merchant = merchant::find($company_id);
$inventory_data = $merchant->products()
    ->whereIn('ptype', ['inventory', 'rawmaterial', 'warranty', 'oilgas','hydrogen'])
    ->whereNotNull('name')
    ->whereIn('id', $ids)
    ->get();

Choose one or the other.

stephen waweru's avatar

@tykus i have used this one

   $merchant = merchant::find($company_id);

$inventory_data = $merchant->products() ->whereIn('ptype', ['inventory', 'rawmaterial', 'warranty', 'oilgas','hydrogen']) ->whereNotNull('name') ->whereIn('id', $ids) ->get();

but am getting an error SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous..what i have understood the 'id' here, ->whereIn('id', $ids), is the cause of the error..i have specified the table as ->whereIn('products.id', $ids) nd it throws an error unknown column

stephen waweru's avatar

@tykus yes it has

  @tykus yes it has 

 public function up()
{
    Schema::create('product', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('systemid');
		$table->string('name')->nullable();
		$table->text('description')->nullable();
		// public/images/product/{product_id}/{photo_1}
		$table->string('photo_1')->nullable();
		// public/images/product/{product_id}/thumb/{thumbnail_1}
		$table->string('thumbnail_1')->nullable();
		$table->string('sku')->nullable();
        $table->enum('ptype',[
			'inventory','services','rawmaterial',
			'voucher','warranty','membership','drum','hydrogen',
			'customization','ecommerce','oilgas'
		])->default('inventory');
		// FK to prd_category.id
		$table->integer('prdcategory_id')->unsigned();
		// FK to prd_subcategory.id
		$table->integer('prdsubcategory_id')->unsigned();
		// FK to prdcategory.id
		$table->integer('prdprdcategory_id')->unsigned();$table->integer('brand_id')->unsigned();
        $table->softDeletes();
        $table->timestamps();
        $table->engine = "ARIA";
    });
}
tykus's avatar

@stephen waweru the table is called product - do you follow any conventions????

This should solve the ambiguity problem, but it doesn't explain why?

$inventory_data = $merchant->products()
    ->whereIn('ptype', ['inventory', 'rawmaterial', 'warranty', 'oilgas','hydrogen'])
    ->whereNotNull('name')
    ->whereIn('product.id', $ids)
    ->get();
stephen waweru's avatar

help my people on how I can find the products of a single company in the function using, the pivot table n a relationship

Please or to participate in this conversation.