knubbe
7 months ago
833
15
Laravel

Sort by latest record column from relations

Posted 7 months ago by knubbe

I have two tables (models) Vehicle and Registration. Vehicle has many registrations and every registrations has start_date and expiry_date and I need to get all vehicles with last registration sort by expiry_date. This is mine Vehicle model part:

/**
  * @return HasMany
  */
  public function registrations() :HasMany
  {
      return $this->hasMany(Registration::class);
  }

    /**
     * @return HasOne
     */
    public function activeRegistration() :HasOne
    {
        return $this->hasOne(Registration::class)->latest();
    }

and I try to solve like this:

Vehicle::with('activeRegistration')->get()->sortBy('activeRegistration.expiry_date')->take(5) // I need only 5 records

but this is not working as I expected. This is part of mine blade file:

@foreach($registrationsVehicle as $vehicle)
    <tr>
        <td>{{ $vehicle->registration }}</td>
        <td>{{ $vehicle->vehicleBrand->name }}</td>
        <td>{{ $vehicle->model }}</td>
        <td>{{ optional($vehicle->activeRegistration)->start_date }}</td>
        <td>{{ optional($vehicle->activeRegistration)->expiry_date }}</td>
    </tr>
@endforeach

I get data but it's not order correctly. How to solve this?

Please sign in or create an account to participate in this conversation.