5 tips for supercharged Laravel Eloquent queries

  Рет қаралды 67,404

Andrew Schmelyun

Andrew Schmelyun

Күн бұрын

In this 16 minute video, I'll show you 5 simple tips and tricks that you can use to enhance your Laravel Eloquent queries, saving time and helping to clean up your code.
Join my newsletter for weekly tips on Laravel + Docker: aschmelyun.substack.com
You'll learn:
- How to build a query on the fly using conditionals
- How to use whereHas to filter out relationships by nested values
- How to create a dynamic attribute and automatically inject it in returned models
Follow me on Twitter! / aschmelyun

Пікірлер: 106
@CyanidePierce90
@CyanidePierce90 3 жыл бұрын
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', '
@aschmelyun
@aschmelyun 3 жыл бұрын
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.
@featurive
@featurive 3 жыл бұрын
Also I would recommend using $request->has() instead of get for if statements.
@CyanidePierce90
@CyanidePierce90 3 жыл бұрын
@@aschmelyun yeh it's much nicer, but we don't know these things until we know them :)
3 жыл бұрын
KZfaq should add code formatting in the comment system... By the way I've learnt about $builder->when() from Reinink (Inertiajs).
@randomguy5922
@randomguy5922 3 жыл бұрын
nice.
@nightpegasus26
@nightpegasus26 Жыл бұрын
Thank you Andrew! Just what I was looking for, but couldn't find anywhere else!
@aschmelyun
@aschmelyun Жыл бұрын
Thanks! I'm glad you liked it!
@tannercampbell
@tannercampbell 3 жыл бұрын
Great video! I am constantly dealing with dates and expirations within my App, tip 5 is gonna be super helpful!
@epslks
@epslks 3 жыл бұрын
I'd looking for tip-two to make a streamlined code for a long time , thanks a lot. Extraordinary !
@user-xf5io2tf3v
@user-xf5io2tf3v 3 жыл бұрын
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
@Shez-dc3fn
@Shez-dc3fn 3 жыл бұрын
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?
@user-xf5io2tf3v
@user-xf5io2tf3v 3 жыл бұрын
@@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.
@laybyyourside
@laybyyourside 3 жыл бұрын
Tip number 4 is what I’ve been seeking for a long time. Thanks a lot
@sumitsharma-us2sl
@sumitsharma-us2sl 3 жыл бұрын
Remember: sortBy won't work with pagination if you are looking for appended column sorted
@bf-xi3om
@bf-xi3om 3 жыл бұрын
Found your channel recently. Good Stuff, keep going.
@ameerhamza4373
@ameerhamza4373 3 жыл бұрын
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
@thebirdhasbeencharged
@thebirdhasbeencharged 3 жыл бұрын
Have you seen Jonathan Reinink's course. Gold! Not to take away from this video however. Wish these existed a couple years ago.
@MohanSingh-pl1mi
@MohanSingh-pl1mi 3 жыл бұрын
I really like the way you are using to elaborate
@brokoli5797
@brokoli5797 3 жыл бұрын
Great tips! saved my time so much.
@JohnnyBigodes
@JohnnyBigodes 3 жыл бұрын
And another great and useful examples. Thank you
@stefanbogdanovic590
@stefanbogdanovic590 3 жыл бұрын
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!
@197syahnur
@197syahnur 3 жыл бұрын
tip 2 is super brand new to me! Thankss
@randomguy5922
@randomguy5922 3 жыл бұрын
Very useful things..........i almost know all of them but its surely some parts where new. Thanks
@AbrahamChavez
@AbrahamChavez 3 жыл бұрын
Great tips Andrew, I'm wondering what keyboard are you using, there is an audible click that I find very satisfying.
@sumitsharma-us2sl
@sumitsharma-us2sl 3 жыл бұрын
Not sure but it 'TVS Gold' sounds same, please check with your hardware and OS compatibility as some models are still mechanical.
@abiyouth_
@abiyouth_ 3 жыл бұрын
Agreed
@simbarashemaunga5575
@simbarashemaunga5575 Жыл бұрын
This was an amazing tutorial!
@gergelygrusz713
@gergelygrusz713 Жыл бұрын
This is brilliant, thank you!
@cultureofnepal2024
@cultureofnepal2024 3 жыл бұрын
Awesome tips. Please post more video on eloquent tips Andrew.
@aschmelyun
@aschmelyun 3 жыл бұрын
I'll have to compile some more and make a part 2!
@cultureofnepal2024
@cultureofnepal2024 3 жыл бұрын
@@aschmelyun please share code too.
@aschmelyun
@aschmelyun 3 жыл бұрын
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
@jailsoncarneiro4936
@jailsoncarneiro4936 2 жыл бұрын
Great Job! Thanks a lot!
@aibarra11
@aibarra11 3 жыл бұрын
for the first optimization, there is also ->when for eloquent queries. No need to write out IF statements
@mithicherbaro9394
@mithicherbaro9394 3 жыл бұрын
Great tips 👍
@Chitte011
@Chitte011 2 жыл бұрын
You are awesome man, great respect for you! (y)
@emadaldeenmukhtar
@emadaldeenmukhtar 3 жыл бұрын
perfect bro, keep it up
@namachivaaya
@namachivaaya 3 жыл бұрын
Nice tips 👍👍👍
@sayedahmadnaweed1
@sayedahmadnaweed1 2 жыл бұрын
You are amazing. Thank you
@pankajbokdia
@pankajbokdia 2 жыл бұрын
Super helpful!
@javieru5871
@javieru5871 2 жыл бұрын
I think for tip 4, we can also use withCount from Lavaravel 5.2.32 or higher.
@sebastianromerolaguna7408
@sebastianromerolaguna7408 2 жыл бұрын
Thanks, it help me.
@iShah300
@iShah300 3 жыл бұрын
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 ...
@jecoy9413
@jecoy9413 3 жыл бұрын
what text editor are you using ?
@mastago3226
@mastago3226 3 жыл бұрын
thank you Andrew
@johnmarkenriquez8808
@johnmarkenriquez8808 3 жыл бұрын
Super helpful..
@yacobee
@yacobee 2 жыл бұрын
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?
@hariharan-wt6qk
@hariharan-wt6qk 3 жыл бұрын
Thanks a lot❤️
@androidbornofficial5148
@androidbornofficial5148 3 жыл бұрын
Amazing video. Please make video Vue js pagination with later with filter queue string.
@davidmucioca6423
@davidmucioca6423 3 жыл бұрын
Very helpful
@rizkihutama5633
@rizkihutama5633 3 жыл бұрын
do you have a video that store json text to database, i'm still strugling with that?
@hossamsalim4426
@hossamsalim4426 3 жыл бұрын
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
@arty4
@arty4 2 жыл бұрын
For tip 1 u can use ->when($expr, $callback) function
@carlosfranciscobenegasbini78
@carlosfranciscobenegasbini78 3 жыл бұрын
Amazinng!
@AdiSK
@AdiSK 3 жыл бұрын
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🙂
@tannercampbell
@tannercampbell 3 жыл бұрын
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!
@TheMessixaviniesta
@TheMessixaviniesta 3 жыл бұрын
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.
@TheMessixaviniesta
@TheMessixaviniesta 3 жыл бұрын
For this particular case.
@TheMessixaviniesta
@TheMessixaviniesta 3 жыл бұрын
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()"
@truongpm2144
@truongpm2144 Жыл бұрын
amazing !!!!
@vaibhavdeokar7642
@vaibhavdeokar7642 3 жыл бұрын
nice video Which extention you use for suggetion
@CyanidePierce90
@CyanidePierce90 3 жыл бұрын
I believe that is PHPStorm, autocomplete is built into it.
@aschmelyun
@aschmelyun 3 жыл бұрын
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.
@silvesterwali6565
@silvesterwali6565 3 жыл бұрын
i love this
@sebastianromerolaguna7408
@sebastianromerolaguna7408 2 жыл бұрын
Have you think in do an tutorial explaining queries for statistics. I haven seen videos about!. Have a good day
@mikevazovsky9211
@mikevazovsky9211 3 жыл бұрын
Good!
@sheenismhaellim2215
@sheenismhaellim2215 3 жыл бұрын
How does the object $poperties know what table to query just by initializing it with Property::query()?
@wsqplm
@wsqplm 3 жыл бұрын
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.
@indeveloperid6061
@indeveloperid6061 3 жыл бұрын
Why we have to write like "uri" or "action" at route code ?
@DRMOHAMEDKHDR
@DRMOHAMEDKHDR 3 жыл бұрын
Thanks alot
@naungyehtet1231
@naungyehtet1231 2 жыл бұрын
Subscribed
@lawrencediokno4883
@lawrencediokno4883 2 жыл бұрын
how are you formatting your return data to look like that?
@guilhermemoraes4055
@guilhermemoraes4055 3 жыл бұрын
What's ".test" on your URL project? Is this somehow online?
@FranckMercado
@FranckMercado 3 жыл бұрын
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.
@sudheertripathi3882
@sudheertripathi3882 2 жыл бұрын
tip3 is fire
@muhammadfahad3483
@muhammadfahad3483 3 жыл бұрын
In the first tip what is ::query() method?
@etokafrancis5700
@etokafrancis5700 3 жыл бұрын
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
@sretksor8689
@sretksor8689 Жыл бұрын
what is the name of IDE that you using in video?
@delita0057
@delita0057 3 жыл бұрын
are you doing nuxt js tutorials?
@aschmelyun
@aschmelyun 3 жыл бұрын
It's on my list, and I'm hoping to have a video showing how to get started with Nuxt pretty soon!
@Arman-cn2tf
@Arman-cn2tf 3 жыл бұрын
Great
@Akimb321
@Akimb321 3 жыл бұрын
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?
@paulmimicry9147
@paulmimicry9147 3 жыл бұрын
How about the amount of query executed?
@grayaahammed917
@grayaahammed917 3 жыл бұрын
What IDE is used in this video please ?
@gobanq
@gobanq 3 жыл бұрын
It’s phpstorm
@loremipsum5642
@loremipsum5642 3 жыл бұрын
Hi, can you provide a github repo for this?
@josegerardosanchezalvarado4703
@josegerardosanchezalvarado4703 2 жыл бұрын
esto me salvo la vida User::whereHas('model', function ($query) { $query->where('propiedad', '!=', 'value'); })->with(['model', 'model'])->get();
@ethanj1533
@ethanj1533 3 жыл бұрын
What ide is that?
@pamithbosilu6055
@pamithbosilu6055 2 жыл бұрын
Laravel Tips and Tricks - kzfaq.info/get/bejne/odycerqi18fDopc.html
@edwinencomienda
@edwinencomienda 3 жыл бұрын
what’s your keyboard 😅?
@aschmelyun
@aschmelyun 3 жыл бұрын
It's a DIY kit I bought and assembled. A GK64 PCB with Kailh Jade Box switches and thick PBT keycaps!
@asim-gandu-phenchod
@asim-gandu-phenchod 2 жыл бұрын
Diamond content
@davidspooner4684
@davidspooner4684 3 жыл бұрын
Way too many commercials interrupting this tutorial. Hard to follow with so many interruptions.
@aschmelyun
@aschmelyun 3 жыл бұрын
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!
@davidspooner4684
@davidspooner4684 3 жыл бұрын
@@aschmelyun Awesome. Thanks for the reply! Otherwise, I really enjoyed your content. Keep it up!
@fractalzombie
@fractalzombie 2 жыл бұрын
Говнокодик конечно… есть ощущение, что только программисты из СНГ заботятся о качестве кода.
@joepalala4757
@joepalala4757 Жыл бұрын
Another tip, You can now use ->latest() in your queries which will getlatest by created date (afaik)
@robertoflores2078
@robertoflores2078 Жыл бұрын
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.
@pamithbosilu6055
@pamithbosilu6055 2 жыл бұрын
Laravel Tips and Tricks - kzfaq.info/get/bejne/odycerqi18fDopc.html
Laravel Eloquent: Deeper Relationships with One Query
10:37
Laravel Daily
Рет қаралды 135 М.
Eloquent or Query Builder: When to Use Which?
5:48
Laravel Daily
Рет қаралды 86 М.
ELE QUEBROU A TAÇA DE FUTEBOL
00:45
Matheus Kriwat
Рет қаралды 23 МЛН
СҰЛТАН СҮЛЕЙМАНДАР | bayGUYS
24:46
bayGUYS
Рет қаралды 762 М.
Eccentric clown jack #short #angel #clown
00:33
Super Beauty team
Рет қаралды 24 МЛН
La final estuvo difícil
00:34
Juan De Dios Pantoja
Рет қаралды 28 МЛН
When to use Traits, Interfaces, and Abstract Classes in PHP
15:08
Andrew Schmelyun
Рет қаралды 15 М.
Can we use Laravel as a Next.js alternative?
20:13
Andrew Schmelyun
Рет қаралды 15 М.
9 Tips for Shorter Laravel Code
10:16
Laravel Daily
Рет қаралды 60 М.
Optimizing Eloquent: Running Out Of Memory?
6:11
Laravel Daily
Рет қаралды 42 М.
You don't need a frontend framework
15:45
Andrew Schmelyun
Рет қаралды 79 М.
Improving Tailwind by doing these 3 things
15:06
Andrew Schmelyun
Рет қаралды 2,7 М.
Laravel's secret weapon: macros (watch me code)
23:46
Aaron Francis
Рет қаралды 16 М.
iPhone 15 Pro vs Samsung s24🤣 #shorts
0:10
Tech Tonics
Рет қаралды 9 МЛН
📱 SAMSUNG, ЧТО С ЛИЦОМ? 🤡
0:46
Яблочный Маньяк
Рет қаралды 1,7 МЛН
Эффект Карбонаро и бумажный телефон
1:01
История одного вокалиста
Рет қаралды 2,6 МЛН