Sort by latest record column from relations

laravel eloquent order by relation column
laravel order by with relation
laravel orderby belongsto relationship
laravel order by relation value
laravel order by relation count
laravel order by nested relationship
laravel order by many to many relationship
laravel relationship default order

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.

You need to add field in latest method:

    public function activeRegistration() :HasOne
    {
        return $this->hasOne(Registration::class)->latest('expiry_date');
    }

If you want to use with('registration'), you need to use closure like this:

$vehicles = Vehicle::with(['registration' => function($relation) {
    $relation->orderBy('expiry_date', 'DESC')->first();
}])->take(5)->get();

For Laravel 5.7 and onwards

if you want to get last registration, you can just use latest('expiry_date'),

it will automatically convert to order by expiry_date desc

$vehicles = Vehicle::with(['registration' => function($relation) {
    $relation->latest('expiry_date')->first();
}])->take(5)->get();

Sort by latest record column from relations, Sort by latest record column from relations. Posted 4 months ago by knubbe. I have two tables (models) Vehicle and Registration . Vehicle has many� To sort values by columns, you can use the SORT function. In the example shown, data is sorted by the Group column. The formula in C8 is: =SORT(C4:L5,2,-1,TRUE) The result is the range C4:L5 sorted by score in descending order.

Get all then use sortBy() function in collection

 Vehicle::with(['activeRegistration'])
        ->all()
        ->sortByDest(function ($vehicle) {
            return $vehicle->activeRegistration->expiry_date;
        });

Eloquent Relations: how to order topics by newest posts?, You can easily order Eloquent results by some column, but what if you want to order by related column in child table? Most common example is� In Classic, from the Record Detail page, you cannot currently sort related lists by columns as a user. The data will always be shown as your admin has configured the sort. *However*, you can press 'Go to list' to go to the full list and on this page you will be able to sort columns as a user.

At the end I solve like this:

return Vehicle::join('registrations', 'vehicles.id','=','registrations.vehicle_id')
            ->has('activeRegistration')
            ->orderBy('registrations.expiry_date')
            ->limit(5)
            ->get();

Ordering database queries by relationship columns in Laravel , In fact, you might want to a order database query by a relationship And finally, we order the records by the company's name column. Then we call the latest() method, which orders the logins to get the most recent record� How to group values of pandas dataframe and select the latest(by date) from each group? For example, given a dataframe sorted by date: id product date 0 220 6647 2014-09-01 1

Working with Databases: Active Record, Yii automatically defines an attribute in Active Record for every column of the an older version of the attribute values and comparing them with the latest one. The task is as simple as declaring a relation method for every interested You see there that customer_id is a property of Order and id is a property of Customer . To sort by one column, you can use the SORT function or SORTBY function. In the example shown, data is sorted by the Group column. The formula in F5 is: =SORT(B5:D14,3) Notice data is sorted in ascending order (A-Z) by default.

Sorting, Filtering, and Relationships, You can sort Access data so you can view records in the order you want to view by applying a filter first to the State field and then to the Last Name field, you� Add an interactive sort button to a column header to enable a user to click the column header and sort the details rows in a table by the value displayed in that column. To add an interactive sort button to a column header to sort the table by value. In report design view, in a table with no groups, right-click the text box in the column header to which you want to add an interactive sort button, and then click Text Box Properties. Click Interactive Sorting. Select Enable interactive sorting

SELECT - Amazon Athena, ORDER BY is evaluated as the last step after any GROUP BY or HAVING clause. BERNOULLI selects each row to be in the table sample with a probability of a JOIN and can reference columns from relations on the left side of the JOIN . Need the ability to sort summary reports by record count in Lightning. (It would be even better to be able to filter by record count. But that's a different Idea.) It's easy to do it in Classic, but as far as I can tell can't be done in LEX.

Comments
  • You can use ORDER BY 'expiry_date'
  • But activeRegistration is the last one as you can see from relationship
  • @knubbe You need to add field in latest method ->latest('expiry_date')
  • I try all combination that you suggest but it's not working
  • plz use the first $this->hasOne(Registration::class)->latest('expiry_date');, and dd($vehicle->activeRegistration()->toSql()), and then post it.
  • "select * from registrations where registrations.vehicle_id = ? and registrations.vehicle_id is not null order by expiry_date desc"