5 tips for supercharged Laravel Eloquent queries

  Рет қаралды 68,298

Andrew Schmelyun

Andrew Schmelyun

Күн бұрын

Пікірлер: 106
@CyanidePierce90
@CyanidePierce90 4 жыл бұрын
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 4 жыл бұрын
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 4 жыл бұрын
Also I would recommend using $request->has() instead of get for if statements.
@CyanidePierce90
@CyanidePierce90 4 жыл бұрын
@@aschmelyun yeh it's much nicer, but we don't know these things until we know them :)
4 жыл бұрын
KZbin should add code formatting in the comment system... By the way I've learnt about $builder->when() from Reinink (Inertiajs).
@randomguy5922
@randomguy5922 4 жыл бұрын
nice.
@AnastasVartanyan
@AnastasVartanyan 4 жыл бұрын
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 4 жыл бұрын
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?
@AnastasVartanyan
@AnastasVartanyan 4 жыл бұрын
@@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.
@aschmelyun
@aschmelyun 4 жыл бұрын
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
@AbrahamChavez
@AbrahamChavez 4 жыл бұрын
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
@nightpegasus26
@nightpegasus26 2 жыл бұрын
Thank you Andrew! Just what I was looking for, but couldn't find anywhere else!
@aschmelyun
@aschmelyun 2 жыл бұрын
Thanks! I'm glad you liked it!
@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.
@aibarra11
@aibarra11 3 жыл бұрын
for the first optimization, there is also ->when for eloquent queries. No need to write out IF statements
@ameerhamza4373
@ameerhamza4373 4 жыл бұрын
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 4 жыл бұрын
Have you seen Jonathan Reinink's course. Gold! Not to take away from this video however. Wish these existed a couple years ago.
@javieru5871
@javieru5871 2 жыл бұрын
I think for tip 4, we can also use withCount from Lavaravel 5.2.32 or higher.
@stefanbogdanovic590
@stefanbogdanovic590 4 жыл бұрын
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!
@josegerardosanchezalvarado4703
@josegerardosanchezalvarado4703 2 жыл бұрын
esto me salvo la vida User::whereHas('model', function ($query) { $query->where('propiedad', '!=', 'value'); })->with(['model', 'model'])->get();
@sebastianromerolaguna7408
@sebastianromerolaguna7408 3 жыл бұрын
Have you think in do an tutorial explaining queries for statistics. I haven seen videos about!. Have a good day
@jecoy9413
@jecoy9413 3 жыл бұрын
what text editor are you using ?
@bf-xi3om
@bf-xi3om 4 жыл бұрын
Found your channel recently. Good Stuff, keep going.
@fractalzombie
@fractalzombie 3 жыл бұрын
Говнокодик конечно… есть ощущение, что только программисты из СНГ заботятся о качестве кода.
@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?
@yacobee
@yacobee 3 жыл бұрын
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?
@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 ...
@tannercampbell
@tannercampbell 4 жыл бұрын
Great video! I am constantly dealing with dates and expirations within my App, tip 5 is gonna be super helpful!
@ehSamurai3483
@ehSamurai3483 3 жыл бұрын
In the first tip what is ::query() method?
@pamithbosilu6055
@pamithbosilu6055 3 жыл бұрын
Laravel Tips and Tricks - kzbin.info/www/bejne/oafPeIqnp8aSqMU
@pamithbosilu6055
@pamithbosilu6055 3 жыл бұрын
Laravel Tips and Tricks - kzbin.info/www/bejne/oafPeIqnp8aSqMU
@sretksor8689
@sretksor8689 2 жыл бұрын
what is the name of IDE that you using in video?
@lawrencediokno4883
@lawrencediokno4883 2 жыл бұрын
how are you formatting your return data to look like that?
@mikevazovsky9211
@mikevazovsky9211 3 жыл бұрын
Good!
@hossamsalim4426
@hossamsalim4426 4 жыл бұрын
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
@randomguy5922
@randomguy5922 4 жыл бұрын
Very useful things..........i almost know all of them but its surely some parts where new. Thanks
@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
@androidbornofficial5148
@androidbornofficial5148 4 жыл бұрын
Amazing video. Please make video Vue js pagination with later with filter queue string.
@rizkihutama5633
@rizkihutama5633 3 жыл бұрын
do you have a video that store json text to database, i'm still strugling with that?
@joepalala4757
@joepalala4757 Жыл бұрын
Another tip, You can now use ->latest() in your queries which will getlatest by created date (afaik)
@arty4
@arty4 3 жыл бұрын
For tip 1 u can use ->when($expr, $callback) function
@gergelygrusz713
@gergelygrusz713 Жыл бұрын
This is brilliant, thank you!
@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!
@hariharan-wt6qk
@hariharan-wt6qk 3 жыл бұрын
Thanks a lot❤️
@epslks
@epslks 3 жыл бұрын
I'd looking for tip-two to make a streamlined code for a long time , thanks a lot. Extraordinary !
@sheenismhaellim2215
@sheenismhaellim2215 4 жыл бұрын
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.
@sayedahmadnaweed1
@sayedahmadnaweed1 2 жыл бұрын
You are amazing. Thank you
@loremipsum5642
@loremipsum5642 3 жыл бұрын
Hi, can you provide a github repo for this?
@robertoflores2078
@robertoflores2078 2 жыл бұрын
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.
@indeveloperid6061
@indeveloperid6061 4 жыл бұрын
Why we have to write like "uri" or "action" at route code ?
@Chitte011
@Chitte011 3 жыл бұрын
You are awesome man, great respect for you! (y)
@sebastianromerolaguna7408
@sebastianromerolaguna7408 3 жыл бұрын
Thanks, it help me.
@DRMOHAMEDKHDR
@DRMOHAMEDKHDR 3 жыл бұрын
Thanks alot
@MohanSingh-pl1mi
@MohanSingh-pl1mi 3 жыл бұрын
I really like the way you are using to elaborate
@pankajbokdia
@pankajbokdia 2 жыл бұрын
Super helpful!
@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!
@paulmimicry9147
@paulmimicry9147 4 жыл бұрын
How about the amount of query executed?
@JohnnyBigodes
@JohnnyBigodes 4 жыл бұрын
And another great and useful examples. Thank you
@simbarashemaunga5575
@simbarashemaunga5575 Жыл бұрын
This was an amazing tutorial!
@asim-gandu-phenchod
@asim-gandu-phenchod 3 жыл бұрын
Diamond content
@jailsoncarneiro4936
@jailsoncarneiro4936 3 жыл бұрын
Great Job! Thanks a lot!
@sudheertripathi3882
@sudheertripathi3882 2 жыл бұрын
tip3 is fire
@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!
@naungyehtet1231
@naungyehtet1231 2 жыл бұрын
Subscribed
@truongpm2144
@truongpm2144 Жыл бұрын
amazing !!!!
@brokoli5797
@brokoli5797 3 жыл бұрын
Great tips! saved my time so much.
@197syahnur
@197syahnur 4 жыл бұрын
tip 2 is super brand new to me! Thankss
@etokafrancis5700
@etokafrancis5700 4 жыл бұрын
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
@AdiSK
@AdiSK 4 жыл бұрын
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 4 жыл бұрын
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 4 жыл бұрын
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 4 жыл бұрын
For this particular case.
@TheMessixaviniesta
@TheMessixaviniesta 4 жыл бұрын
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()"
@grayaahammed917
@grayaahammed917 4 жыл бұрын
What IDE is used in this video please ?
@gobanq
@gobanq 3 жыл бұрын
It’s phpstorm
@ethanj1533
@ethanj1533 3 жыл бұрын
What ide is that?
@namachivaaya
@namachivaaya 4 жыл бұрын
Nice tips 👍👍👍
@silvesterwali6565
@silvesterwali6565 3 жыл бұрын
i love this
@mastago3226
@mastago3226 4 жыл бұрын
thank you Andrew
@johnmarkenriquez8808
@johnmarkenriquez8808 4 жыл бұрын
Super helpful..
@carlosfranciscobenegasbini78
@carlosfranciscobenegasbini78 3 жыл бұрын
Amazinng!
@davidmucioca6423
@davidmucioca6423 4 жыл бұрын
Very helpful
@cultureofnepal2024
@cultureofnepal2024 4 жыл бұрын
Awesome tips. Please post more video on eloquent tips Andrew.
@aschmelyun
@aschmelyun 4 жыл бұрын
I'll have to compile some more and make a part 2!
@cultureofnepal2024
@cultureofnepal2024 4 жыл бұрын
@@aschmelyun please share code too.
@emadaldeenmukhtar
@emadaldeenmukhtar 4 жыл бұрын
perfect bro, keep it up
@Arman-cn2tf
@Arman-cn2tf 4 жыл бұрын
Great
@mithicherbaro9394
@mithicherbaro9394 4 жыл бұрын
Great tips 👍
@vaibhavdeokar7642
@vaibhavdeokar7642 4 жыл бұрын
nice video Which extention you use for suggetion
@CyanidePierce90
@CyanidePierce90 4 жыл бұрын
I believe that is PHPStorm, autocomplete is built into it.
@aschmelyun
@aschmelyun 4 жыл бұрын
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.
I built an app using a single index.php file, here's how it went
32:42
Andrew Schmelyun
Рет қаралды 62 М.
Execute Code After a Response is Returned?
14:00
Laracasts
Рет қаралды 8 М.
💩Поу и Поулина ☠️МОЧАТ 😖Хмурых Тварей?!
00:34
Ной Анимация
Рет қаралды 2 МЛН
Офицер, я всё объясню
01:00
История одного вокалиста
Рет қаралды 4,8 МЛН
Laravel Eloquent: Deeper Relationships with One Query
10:37
Laravel Daily
Рет қаралды 141 М.
PHP on the frontend! No more Javascript!
14:47
Aaron Francis
Рет қаралды 123 М.
React visually explained: 'use client'
15:57
Delba
Рет қаралды 32 М.
Improving Tailwind by doing these 3 things
15:06
Andrew Schmelyun
Рет қаралды 3 М.
9 Tips for Shorter Laravel Code
10:16
Laravel Daily
Рет қаралды 61 М.
Populating Google Maps with Vue and Laravel
25:17
Andrew Schmelyun
Рет қаралды 23 М.
Serverless PHP is pretty good
12:33
Andrew Schmelyun
Рет қаралды 7 М.
Organizing data with Laravel Collections
32:51
Andrew Schmelyun
Рет қаралды 27 М.
STOP Learning These Programming Languages (for Beginners)
5:25
Andy Sterkowitz
Рет қаралды 700 М.
"The Life & Death of htmx" by Alexander Petros at Big Sky Dev Con 2024
23:01
Montana Programmers
Рет қаралды 61 М.