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.
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.
This is so funny..... after 3 years !
ask a stupid question, you get a stupid answer...
Please sign in or create an account to participate in this conversation.