Home > Back-end >  Call to a member function trashed() on null
Call to a member function trashed() on null

Time:03-20

Everything works fine without basket-add button, but when I added it i have error "Call to a member function trashed() on null". Here is my code:

card.blade.php

<p>{{ $sku->price }} {{ $currencySymbol }}</p>
<p>
<form action="{{ route('basket-add', $sku) }}" method="POST">
  @if($sku->isAvailable() && Auth::check())
    <button type="submit"  role="button">
      @lang('main.add_to_basket')
    </button> -->
  @else
    @lang('main.not_available')
  @endif
  <a href="{{ route('sku', [
    isset($category)
      ? $category->code
      : !empty($sku->product->category)
        ? $sku->product->category->code
        : '' ,
    $sku->product->code, $sku->id
  ]) }}"  role="button">@lang('main.more')</a>
  @csrf
</form>

Sku.php

public function isAvailable()
{
    return !$this->product->trashed() && $this->count > 0;
}

What is a problem? all pages work fine (I am doing pagination) except 5 and 7.

Models:

class Sku extends Model
{
    use SoftDeletes;

    protected $fillable = ['product_id', 'count', 'price'];
    protected $visible = ['id', 'count', 'price', 'product_name'];

    public function product()
    {
        return $this->belongsTo(Product::class);
    }

Product.php

class Product extends Model
{
    use SoftDeletes, Translatable;

    protected $fillable = [
        'name', 'code', 'price', 'category_id', 'description', 'image', 'hit', 'new', 'recommend', 'count', 'name_en',
        'description_en'
    ];

    public function category()
    {
        return $this->belongsTo(Category::class);
    }

CodePudding user response:

when calling the QueryBuilder methods you need to access via method names. Acsessing via property will not work. Change product property to method product()

public function isAvailable()
    {
        return !$this->product()->trashed() && $this->count > 0;
    }

CodePudding user response:

Seems like in places you use $this->product or $sku->product, the related product might not exist, meaning either the product is deleted in your database or the Sku model's product_id is null. So wherever you're trying to access the product relationship of a Sku model, you should check for its existence.

  • Related