To add to tip 1. If you want to avoid "if" blocks, you can use the eloquent "when" method. return Property::query() ->when($request->get('rent'), function ($query) use ($request) { return $query->where('rent', 'when($request->get('rent'), fn($query) => $query->where('rent', '
If you'd like to see the full source code behind this video, I've created a repo for it here: github.com/aschmelyun/video-5-laravel-eloquent-tips Also, if you'd like to directly support these videos and open-source projects, consider sponsoring me on GitHub: github.com/sponsors/aschmelyun
The Tip four that adds requests count attribute will cause extra db call for each technician since to compute the model attributes aggregate query will be executed. To deal with this problem you can use Laravel Eloquent Query Builder `withCount` method like->withCount('requests'). The method will add requests_count attribute for each model with single query
alternatively he could just do $this->requests->count() in the accessor since your method means laravel might make two calls one for withCount and one for with?
@@Shez-dc3fn surely you can do this way too, but in that case you need to make sure that your relation is always loaded, if not the accessor will be querying the db. Also this way you force the count to be calculated in the collection, this means that php will count your relations and that can take some resources and memory if the count is huge, so I would prefer using withCount that will count the relations using SQL SUM aggregation, it will take a lot less resources with big data.
I haven't watched complete video but still i believe that this is going to be one of the best video on eloquent... Much love for you keep up the good work
Awesome video, I have suggestion you could make a new custom Request for example TenantSearchRequest and you should make all query parameters nullable and add string boolean validation etc, so you could get only those that are inside the request so you don't have to be scared if someone sends you a parameter you don't expect in you API for an example, and you get those parameters with $request->validated() and apply same logic. And one more since you are using PHP storm use laravel ide helper to generate models annotations for intellisense, and you can access requests_count dynamic fields. Cheers mate!
Tip 1: You could also use Laravel pipelines. It abstracts the 'ifs' into classes. If you need to add more filters, you just create a new class without modifying your controller classes app(Pipeline::class) ->send($this->model->query()) ->through( Client::class, CallStatus::class , Sort::class )->thenReturn()->get(); An example: It filters this model by client_id, call_status and then sorts them. The filters are run only when they are present in the request
Hi andrew Great tips however i have a question Hoe about including join if conditiions is true Like if a request comes so i want to join a new table into existing eloquent query ...
Thank you, how queries from relations e.g, products belong to a category and products also belongs to a type, how to get query of categories that their products have a specific type?
I believe there is no information about ::query method in Laravel docs (your first tip). It's an awesome tip, but I can't believe there's no info about this. Or I missed it?
Hi, thanks for the tips. I have one doubt, why not use built in withCount method to get the count on tip 4 How is your method better than the built in method. Great videos by the way🙂
I think creating a model attribute is better in most scenarios to do this, it’s a bit more reusable if your response is returning more then the count. But you make good point that method works well too!
Actually it would still make one query for each model even with eager loading because he's using the method "$this->requests()->count()" it would only be acceptable if replaced with "$this->requests->count()"
Could you help please - I have inventory system with 2 models (invoice) with relationship items morphMany Item model I need to get item record with MAX date of purchase
Grabbed from laravel docs: By convention, the "snake case", plural name of the class will be used as the table name unless another name is explicitly specified. So, in this case, Eloquent will assume the Property model stores records in the properties table.
I've been using Mehradsadeghi\FilterQueryString for years. Forget about if's and when's. Let the library do all that work for you. I can't find a cleaner way to do it.
To add to tip 1. If you want to avoid "if" blocks, you can use the eloquent "when" method.
return Property::query()
->when($request->get('rent'), function ($query) use ($request) {
return $query->where('rent', 'when($request->get('rent'), fn($query) => $query->where('rent', '
Just learned about the when() method from someone on dev.to! I'll definitely be keeping this in mind, as that's a way cleaner syntax.
Also I would recommend using $request->has() instead of get for if statements.
@@aschmelyun yeh it's much nicer, but we don't know these things until we know them :)
UA-cam should add code formatting in the comment system... By the way I've learnt about $builder->when() from Reinink (Inertiajs).
nice.
If you'd like to see the full source code behind this video, I've created a repo for it here: github.com/aschmelyun/video-5-laravel-eloquent-tips
Also, if you'd like to directly support these videos and open-source projects, consider sponsoring me on GitHub: github.com/sponsors/aschmelyun
Thank you Andrew! Just what I was looking for, but couldn't find anywhere else!
Thanks! I'm glad you liked it!
The Tip four that adds requests count attribute will cause extra db call for each technician since to compute the model attributes aggregate query will be executed. To deal with this problem you can use Laravel Eloquent Query Builder `withCount` method like->withCount('requests'). The method will add requests_count attribute for each model with single query
alternatively he could just do $this->requests->count() in the accessor since your method means laravel might make two calls one for withCount and one for with?
@@Shez-dc3fn surely you can do this way too, but in that case you need to make sure that your relation is always loaded, if not the accessor will be querying the db. Also this way you force the count to be calculated in the collection, this means that php will count your relations and that can take some resources and memory if the count is huge, so I would prefer using withCount that will count the relations using SQL SUM aggregation, it will take a lot less resources with big data.
I haven't watched complete video but still i believe that this is going to be one of the best video on eloquent... Much love for you keep up the good work
Have you seen Jonathan Reinink's course. Gold! Not to take away from this video however. Wish these existed a couple years ago.
Great tips Andrew, I'm wondering what keyboard are you using, there is an audible click that I find very satisfying.
Not sure but it 'TVS Gold' sounds same, please check with your hardware and OS compatibility as some models are still mechanical.
Agreed
Tip number 4 is what I’ve been seeking for a long time. Thanks a lot
Remember: sortBy won't work with pagination if you are looking for appended column sorted
Awesome video, I have suggestion you could make a new custom Request for example TenantSearchRequest and you should make all query parameters nullable and add string boolean validation etc, so you could get only those that are inside the request so you don't have to be scared if someone sends you a parameter you don't expect in you API for an example, and you get those parameters with $request->validated() and apply same logic. And one more since you are using PHP storm use laravel ide helper to generate models annotations for intellisense, and you can access requests_count dynamic fields. Cheers mate!
I'd looking for tip-two to make a streamlined code for a long time , thanks a lot.
Extraordinary !
I really like the way you are using to elaborate
Great video! I am constantly dealing with dates and expirations within my App, tip 5 is gonna be super helpful!
Found your channel recently. Good Stuff, keep going.
for the first optimization, there is also ->when for eloquent queries. No need to write out IF statements
Laravel Tips and Tricks - ua-cam.com/video/kvlGWqra_rc/v-deo.html
Very useful things..........i almost know all of them but its surely some parts where new. Thanks
Awesome tips. Please post more video on eloquent tips Andrew.
I'll have to compile some more and make a part 2!
@@aschmelyun please share code too.
This is brilliant, thank you!
Have you think in do an tutorial explaining queries for statistics. I haven seen videos about!.
Have a good day
I think for tip 4, we can also use withCount from Lavaravel 5.2.32 or higher.
This was an amazing tutorial!
Tip 1:
You could also use Laravel pipelines. It abstracts the 'ifs' into classes. If you need to add more filters, you just create a new class without modifying your controller classes
app(Pipeline::class)
->send($this->model->query())
->through(
Client::class,
CallStatus::class
,
Sort::class
)->thenReturn()->get();
An example: It filters this model by client_id, call_status and then sorts them. The filters are run only when they are present in the request
Great tips! saved my time so much.
what text editor are you using ?
Nice job, thanks
Hi andrew
Great tips however i have a question
Hoe about including join if conditiions is true
Like if a request comes so i want to join a new table into existing eloquent query ...
You are amazing. Thank you
Thank you, how queries from relations e.g, products belong to a category and products also belongs to a type, how to get query of categories that their products have a specific type?
tip 2 is super brand new to me! Thankss
Great Job! Thanks a lot!
And another great and useful examples. Thank you
What's ".test" on your URL project? Is this somehow online?
It's a local custom domain he setup in his computer. In Linux you can do it by adding your domain to /etc/hosts file.
Super helpful!
Thanks, it help me.
I believe there is no information about ::query method in Laravel docs (your first tip). It's an awesome tip, but I can't believe there's no info about this. Or I missed it?
For tip 1 u can use ->when($expr, $callback) function
how are you formatting your return data to look like that?
You are awesome man, great respect for you! (y)
Amazing video. Please make video
Vue js pagination with later with filter queue string.
Hi, thanks for the tips.
I have one doubt, why not use built in withCount method to get the count on tip 4
How is your method better than the built in method.
Great videos by the way🙂
I think creating a model attribute is better in most scenarios to do this, it’s a bit more reusable if your response is returning more then the count. But you make good point that method works well too!
The built in method is way better because with tip 4 you have to ALWAYS eager load the relationship or you will end up with a bunch of queries.
For this particular case.
Actually it would still make one query for each model even with eager loading because he's using the method "$this->requests()->count()" it would only be acceptable if replaced with "$this->requests->count()"
what is the name of IDE that you using in video?
do you have a video that store json text to database, i'm still strugling with that?
Nice tips 👍👍👍
Good!
Thanks a lot❤️
In the first tip what is ::query() method?
Could you help please - I have inventory system with 2 models (invoice) with relationship items morphMany Item model I need to get item record with MAX date of purchase
are you doing nuxt js tutorials?
It's on my list, and I'm hoping to have a video showing how to get started with Nuxt pretty soon!
Great tips 👍
nice video
Which extention you use for suggetion
I believe that is PHPStorm, autocomplete is built into it.
Correct, my IDE is PHPStorm. If you're asking about the suggestions in the terminal window, I'm using a ZSH plugin called zsh-autosuggestions.
thank you Andrew
perfect bro, keep it up
Why we have to write like "uri" or "action" at route code ?
amazing !!!!
Thanks alot
Very helpful
Another tip, You can now use ->latest() in your queries which will getlatest by created date (afaik)
How does the object $poperties know what table to query just by initializing it with Property::query()?
Grabbed from laravel docs: By convention, the "snake case", plural name of the class will be used as the table name unless another name is explicitly specified. So, in this case, Eloquent will assume the Property model stores records in the properties table.
Super helpful..
tip3 is fire
How about the amount of query executed?
Amazinng!
Subscribed
Hi, can you provide a github repo for this?
i love this
what’s your keyboard 😅?
It's a DIY kit I bought and assembled. A GK64 PCB with Kailh Jade Box switches and thick PBT keycaps!
What IDE is used in this video please ?
It’s phpstorm
esto me salvo la vida User::whereHas('model', function ($query) {
$query->where('propiedad', '!=', 'value');
})->with(['model', 'model'])->get();
What ide is that?
Diamond content
Great
Way too many commercials interrupting this tutorial. Hard to follow with so many interruptions.
Hey David, I'm really sorry about that. I'll see if I can tone them down across my channel. Thanks for letting me know!
@@aschmelyun Awesome. Thanks for the reply! Otherwise, I really enjoyed your content. Keep it up!
Говнокодик конечно… есть ощущение, что только программисты из СНГ заботятся о качестве кода.
I've been using Mehradsadeghi\FilterQueryString for years. Forget about if's and when's. Let the library do all that work for you. I can't find a cleaner way to do it.
Laravel Tips and Tricks - ua-cam.com/video/kvlGWqra_rc/v-deo.html