0

I am trying to use the following functions to display a stock level flag on using a Twig view template. But I am getting the following error: LogicException Cart\Models\Product::hasLowStock must return a relationship instance. I've been researching this for a while and can't find a fix. I'm relatively new to php.

Here's my code:

namespace Cart\Models;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    public function hasLowStock()
    {
        if($this->outOfStock()) {
            return false;
        }

        return (bool) $this->stock <= 5;
    }

    public function outOfStock()
    {
        return $this->stock === 0;
    }

    public function inStock()
    {
        return $this->stock >= 1;
    }

    public function hasStock($quantity)
    {
        return $this->stock >= $quantity;
    }
}

And here's the twig view I'm using to display the product/stock: {% extends 'templates/app.twig' %}

{% block content %}
    <div class="container mt-4">
        <div class="row">
            <div class="col-md-6">
                <img src="{{ product.image }}" alt="{{ product.title }} image." class="card img-fluid">
            </div>
        <div class="col-md-6">
            {% if product.hasLowStock %}
                <span class="label label-warning">Low stock</span>
            {% endif %}

            {% if product.outOfStock %}
                <span class="label label-danger">Out of stock</span>
            {% endif %}

            {% if product.inStock %}
                <span class="label label-danger">Out of stock</span>
            {% endif %}
            <h3>{{ product.title }}</h3>
            <p>{{ product.description }}</p>
        </div>
        </div>
    </div>

{% endblock %}
txujci13
  • 13
  • 3

1 Answers1

1

hasLowStock() etc. are methods, not properties:

{% if product.hasLowStock() %}
{% if product.outOfStock() %}
{% if product.inStock() %}

You can also use accessors:

public function getHasLowStockAttribute()
{
    [...]
}

Then you can access them as properties:

{% if product.hasLowStock %}
Jonas Staudenmeir
  • 24,815
  • 6
  • 63
  • 109