DEV Community

Cover image for Laravel Relationship Recipes: Simplify Querying with newestOfMany
Muhammad Saim
Muhammad Saim

Posted on

Laravel Relationship Recipes: Simplify Querying with newestOfMany

Laravel Relationship Recipes: Simplify Querying with newestOfMany

Welcome back to our Laravel Relationship Recipes series! Today, we're introducing another handy method in Laravel Eloquent relationships: newestOfMany. This method simplifies querying for the newest model in a hasMany relationship.

Understanding the Scenario

Consider the scenario where you have an Employee model with a hasMany relationship to Paycheck models. You constantly need to retrieve the newest paycheck for each employee.

Introducing the newestOfMany Method

Similar to oldestOfMany, you can create a relationship method for the newest model in your Employee model:

class Employee extends Model
{
    public function latestPaycheck()
    {
        return $this->hasOne(Paycheck::class)->latestOfMany();
    }
}
Enter fullscreen mode Exit fullscreen mode

By using the hasOne method and chaining latestOfMany, Laravel will automatically retrieve the newest paycheck for each employee.

Limitations

As with oldestOfMany, it's important to note that the newestOfMany method relies on auto-increment IDs to determine the newest model. If you're using UUIDs as foreign keys, this method won't work as expected.

Conclusion

The newestOfMany method in Laravel Eloquent relationships provides a convenient way to retrieve the newest model in a hasMany relationship without the need for custom queries. By leveraging this method, you can simplify your code and improve maintainability.

Stay tuned for more Laravel Relationship Recipes in this series, where we'll continue to explore useful methods for working with Eloquent relationships!

Top comments (1)

Collapse
 
xwero profile image
david duymelinck • Edited

I can understand why the default is id, because that is the column that is the most likely to exist.

But if you know the table is going to be queried by order you can use $this->timestamps() in the table migration. And then you can do $this->hasOne(Paycheck::class)->latestOfMany('created_at') .

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay