Profile picture of Martin Joo

Martin Joo

@mmartin_joo

Published: April 8, 2025
1
3
20

šŸ”„Level up your Eloquent game In this thread, you can read about 5 pretty useful but not so well-known Eloquent features such as: - whereBelongsTo - whereRelation - Default relationship values 🧵Keep Reading

Image in tweet by Martin Joo

1/6 whereRelation You can use the whereRelation helper to filter records based on Eloquent relationships. It uses EXISTS in the background so it’s an excellent choice if you don’t need data from the related record:

Image in tweet by Martin Joo

2/6 whereBelongsTo With the whereBelongsTo helper, your code reads like an English sentence. Just take a look at this:

Image in tweet by Martin Joo

3/6 oldestOfMany If you often need the oldest record from a related table, you can use the oldestOfMany relationship type. It feels a bit more ā€œnativeā€ than writing a regular query. This will return the oldest paycheck (based on the smallest auto-increment ID) for an employee:

Image in tweet by Martin Joo

4/6 Default attribute values Did you know that you can give default values for model attributes? Check this out:

Image in tweet by Martin Joo

5/6 Default relationships Not only for attributes, but you can also give default values for relationships. Easy as usual:

Image in tweet by Martin Joo

6/6 Thank you, if you're still here! Just released a new book - Building a database engine Check it out here: https://thedatabasebook.com/

Share this thread

Read on Twitter

View original thread

Navigate thread

1/7