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 %}