I’m working on a project using Laravel 10.
My goal is to show all customers
data and added with a field containing the date of the last penawaran
data made by that customer. Each Customer can create multiple Penawaran, but each Penawaran always have only one Customer.
The problem I’m encountering is when $row->updated_at
variable is printed out in the views, it shows the updated_at
of the customers
record instead.
what am I doing wrong? any help is appreciated.
this is my code:
migrations/..create_penawarans_table
:
$table->id();
$table->unsignedBigInteger('customer_id');
$table->unsignedBigInteger('user_id');
$table->timestamps();
migrations/..create_customers_table
:
$table->id();
$table->string('nama');
$table->string('alamat');
$table->string('telepon');
$table->string('email')->nullable();
$table->string('slug')->unique();
$table->timestamps();
models/Customer.php
:
public function penawaran()
{
return $this->belongsTo(Penawaran::class);
}
models/Penawaran.php
:
public function customer()
{
return $this->hasMany(Customer::class, 'customer_id');
}
PenawaranController.php
:
public function index()
{
$data = Customer::orderBy('nama', 'ASC')
->with(['penawaran' => function ($query) {
$query->whereNotNull('updated_at');
$query->orderBy('updated_at', 'desc');
}]);
$view_data = [
'page_title' => 'List Customer',
'active' => 'customer',
'data' => $data->get(),
];
return view('customer.index', $view_data);
}
views/customer/index.blade.php
:
//
@foreach ($data as $row)
<tr>
<td class="px-2 fit">{{ $loop->index + 1 }}.</td>
<td>{{ $row->nama }}</td>
<td class="fit">{{ $row->telepon }}</td>
<td class="fit">{{ date('d F Y H:i:s', strtotime($row->updated_at)); }}</td>
</tr>
@endforeach
//
2
Answers
okay so first of all if the Customer has many Penawaran then you can not do belongs to in the Customer model, you will have hasMany in the Customer and belongs to Customer in the Penawaran model.
In the Customer Model,
The above relationship will give the collection of many penawarans records that will belongs to the particular customer but if you want the latest record then define another relationship hasOne,
In the Penawaran Model,
Then in the method index,
And then the blade,
in models/Customer.php,it should be