Punyapal Shah ☁️ 🦹 Laravel Artisan
Punyapal Shah ☁️ 🦹 Laravel Artisan

@MrPunyapal

9 Tweets 12 reads Apr 02, 2024
πŸš€ Laravel developers, did you know you can supercharge your Eloquent models with custom builders?
You can even override existing methods. 🀯
let's see how using a Post model and PostBuilder. πŸ™Œ#Laravel #Eloquent #PHP
Create a custom builder class PostBuilder that extends Laravel's base Builder class.
Implement custom methods inside the PostBuilder class for common query logic, including overriding existing methods.
Override the newEloquentBuilder method in your model to return an instance of your custom builder.
Start using your custom builder methods in your application!
now let's solve a real issue by using the same method.
`withAggregate` is not documented but it is widely used by the community. but as it is used by withSum, withMax, withCount, etc we have intentionally removed orderings.
as you can see here: #L659-L663" target="_blank" rel="noopener" onclick="event.stopPropagation()">github.com
because of this if we try to get the last comment from the comments relationship we cannot do it as orders are removed intentionally and we end up getting the first comment in place of the last comment shown in the code block.
here is how to use it:
we can copy and paste the code `withAggregate` into our `PostBuilder` with changes that we have done to make `withAggregate` work for ordering the columns.
And out of the box, it will work with `loadAggregate` too as `loadAggregate` uses `withAggregate` behind the scenes.
That's it!
You've now leveled up your Laravel Eloquent skills with custom builders.
Keep exploring and building awesome things with Laravel! πŸ”πŸ’»
#PHP #Laravel

Loading suggestions...