Search code examples
phplaraveleloquenteloquent-relationship

How to display the most recent single record in laravel using eloquent


How can i display the most recent single record in laravel using eloquent the solution i have shown below only shows the oldest record in the database not the most recent.

I have two tables a payments table and tenants table. payments table has the following columns

  • id
  • amount
  • rent_from
  • rent_to

Payments table has a many to one relationship with the tenants table.

In my index page i wish to only display the latest payment per tenant (tenant_id)

In my controller i have

public function index() {
  $payments = Payment::groupBy('tenant_id')->get();
  return view('payments.index')->with('payments',$payments);
}

index.blade.php

@foreach ($payments as $post)
  {{ $post->id }}
  {{ $post->amount }}
  {{ $post->rent_from }}
  {{ $post->rent_to }}
  {{ $post->tenant['name'] }}
@endforeach    

This show the oldest record not the latest. How can i display the most recent payment record for each tenant - only one most recent payment record per tenant_id


Solution

  • you could make a new relation called 'lastPayment' by using 'hasOne' with orderByDesc to get the last payment ....

    class Tenant extends Model
    {
    public function lastPayment()
    {
     return $this->hasOne(Payment::class,'tenant_id')->orderByDesc('payments.id');
    }
    }
    
     public function index()
        {
     $tenants= Tenant ::with('lastPayment')->get();
    return view('payments.index')->with('tenants',$tenants);
       
        }