I have three tables. Sales, Services, and Customers. I've set up the relationship between the three tables. When I save a sale in the database, the id of the customer and service is saved. Currently, I have been able to get the related data from the customer and service table based on the sales table. but I have a problem displaying them in my blade file.
This is my sales controller
public function index()
{
$sales = Sale::all();
foreach($sales as $sale){
$customer_car_reg_no[] = $sale->customer->car_reg_no;
$service_name[] = $sale->service->name;
}
return view('adminlte.sales.index', compact('sales', 'customer_car_reg_no', 'service_name'));
}
When i remove the "[ ]" attached to the variables, it only displays the last item in the array. When i leave them there i get this error
htmlspecialchars() expects parameter 1 to be string, array given (View: C:\code\Valet\resources\views\adminlte\sales\index.blade.php)
This is my blade file
<table class="table table-striped projects">
<thead>
<tr>
<th style="width: 1%">
S/N
</th>
<th style="width: 20%">
Car Reg No
</th>
<th style="width: 20%">
Service(s)
</th>
<th style="width: 20%">
Washed By
</th>
<th style="width: 10%">
Date
</th>
<th style="width: 8%" >
Total
</th>
</tr>
</thead>
<tbody>
@foreach($sales as $sale)
<tr>
<td>
{{$loop->iteration}}
</td>
<td>
{{$customer_car_reg_no}}
</td>
<td>
{{$service_name}}
</td>
<td>
{{$sale->washer}}
</td>
<td>
{{$sale->date}}
</td>
<td>
{{$sale->total}}
</td>
</tr>
@endforeach
</tbody>
</table>
This is my migration file
public function up()
{
Schema::create('sales', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('customer_id');
$table->foreign('customer_id')->references('id')->on('customers');
$table->unsignedBigInteger('service_id');
$table->foreign('service_id')->references('id')->on('services');
$table->date('date');
$table->string('washer');
$table->decimal('total', 8, 2);
$table->timestamps();
});
}