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

shahr's avatar
Level 10

How to display `business_name` from the orders table?

I want to display business_name from the orders table.

orders table

public function up()
{
    Schema::create('orders', function (Blueprint $table) {
        $table->id();
        $table->foreignId('user_id')->constrained()->cascadeOnDelete();
        $table->string('business_name')->nullable();
        $table->tinyInteger('business_type')->nullable();
        $table->integer('phone_number')->nullable();
        $table->integer('national_code')->nullable();
        $table->integer('postal_code')->nullable();
        $table->string('email')->nullable();
        $table->tinyInteger('discount_code')->nullable();
        $table->text('address')->nullable();
        $table->timestamps();
    });
}

User.php

public function orders()
{
    return $this->hasMany(Order::class);
}

OrderController.php

public function index()
{
    $orders = User::with('orders')->get();
    return view('Admin.orders.index', compact('orders'));
}

index.blade.php

@foreach($orders as $order)
    <tr>
        <td>{{ $order->product }}</td>
        <td>{{ $order->business_name }}</td>
        <td>{{ $order->business_type }}</td>
        <td>{{ $order->phone_number }}</td>
        <td>{{ $order->user }}</td>
        <td>{{ $order->accounting_code }}</td>
    </tr>
@endforeach

I didn't see any data from the database.

0 likes
4 replies
LaryAI's avatar
Level 58

The issue is that the business_name field is in the orders table, but the code is trying to access it directly from the User model. To fix this, you need to loop through the orders relationship for each user and access the business_name field from there. Here's an updated version of the index.blade.php file:

@foreach($orders as $user)
    @foreach($user->orders as $order)
        <tr>
            <td>{{ $order->product }}</td>
            <td>{{ $order->business_name }}</td>
            <td>{{ $order->business_type }}</td>
            <td>{{ $order->phone_number }}</td>
            <td>{{ $user->name }}</td>
            <td>{{ $order->accounting_code }}</td>
        </tr>
    @endforeach
@endforeach

This code loops through each user, and then loops through each order for that user. It then displays the relevant fields for each order, including the business_name field.

Snapey's avatar

This is so funny..... after 3 years !

Snapey's avatar

ask a stupid question, you get a stupid answer...

Please or to participate in this conversation.