Search code examples
phplaraveleloquenteloquent-relationship

Laravel throws an error once I have more than 15 rows in my order table ```local.ERROR: Undefined array key 0```


I really don't know how to put it. I have two tables Order.php and Product.php, a return $this->hasMany(Product::class, 'id'); in Order.php and return $this->belongsTo(Order::class, 'product_id'); in Product.php.

In my OrderController

public function index()
{
    $orders = Order::latest()->paginate(10);
    return view('admin.order.order')->with([
        'orders' => $orders,
    ]);
}

in my view

@foreach($orders as $order)
    <tr data-href="{{ route('orders.view', $order->id) }}">
        <td></td>
        <td>{{ $order->products[0]->product_name }}</td>
        <td>{{ $order->order_quantity }}</td>
        <td>{{ $order->customer_name }}</td>
        <td>{{ $order->customer_tel_no }}</td>
        <td width="300">{{ $order->customer_address }} Lorem ipsum dolor sit amet, consectetur adipisicing elit.</td>
        <td>{{ $order->total_amount }}</td>
        <td>
            <span class="badge text-white badge-lg bg-{{ $order->is_delivered == false ? 'warning' : 'success' }}">
                {{ $order->is_delivered == false ? 'Not yet delivered!' : 'Delivered!' }}
            </span>
        </td>
        <td>{{ $order->created_at->diffForHumans() }}</td>
    </tr>
@endforeach

Everything works fine until, when I have more than 15 records in the orders table I get an error Undefined array key 0

And please I'm also new to Laravel thanks


Solution

  • I would think this happens because of the line:

    <td>{{ $order->products[0]->product_name }}</td>

    Are you sure you have a product for every order?

    This error would be because an $order does not have any products, therefore would have no array key 0

    You can make use use php's new optional syntax while chaining which is ?-> https://stitcher.io/blog/php-8-nullsafe-operator

    $order->products?->first()->product_name which should return null, if there aren't any products on this particular $order (assuming you are using php 8!)

    If you are on an older version of php you should consider

    @if(count($order->products))
    <td>{{ $order->products[0]->product_name }}</td>
    @endif
    

    Yet another approach would be, to use laravel's optional() helper like below

    <td>{{ optional($order->products)->first()->product_name }} </td>