5 tips for supercharged Laravel Eloquent queries

Поділитися
Вставка
  • Опубліковано 27 жов 2024

КОМЕНТАРІ • 107

  • @CyanidePierce90
    @CyanidePierce90 4 роки тому +49

    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 роки тому +7

      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 роки тому +6

      Also I would recommend using $request->has() instead of get for if statements.

    • @CyanidePierce90
      @CyanidePierce90 4 роки тому +1

      @@aschmelyun yeh it's much nicer, but we don't know these things until we know them :)

    •  4 роки тому +1

      UA-cam should add code formatting in the comment system... By the way I've learnt about $builder->when() from Reinink (Inertiajs).

    • @randomguy5922
      @randomguy5922 4 роки тому

      nice.

  • @aschmelyun
    @aschmelyun  4 роки тому +5

    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

  • @nightpegasus26
    @nightpegasus26 2 роки тому +3

    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!

  • @AnastasVartanyan
    @AnastasVartanyan 4 роки тому +5

    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.

  • @ameerhamza4373
    @ameerhamza4373 4 роки тому +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 4 роки тому

      Have you seen Jonathan Reinink's course. Gold! Not to take away from this video however. Wish these existed a couple years ago.

  • @AbrahamChavez
    @AbrahamChavez 4 роки тому +11

    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

  • @laybyyourside
    @laybyyourside 3 роки тому +1

    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

  • @stefanbogdanovic590
    @stefanbogdanovic590 4 роки тому +1

    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!

  • @epslks
    @epslks 3 роки тому

    I'd looking for tip-two to make a streamlined code for a long time , thanks a lot.
    Extraordinary !

  • @MohanSingh-pl1mi
    @MohanSingh-pl1mi 3 роки тому

    I really like the way you are using to elaborate

  • @tannercampbell
    @tannercampbell 4 роки тому +1

    Great video! I am constantly dealing with dates and expirations within my App, tip 5 is gonna be super helpful!

  • @bf-xi3om
    @bf-xi3om 4 роки тому +2

    Found your channel recently. Good Stuff, keep going.

  • @aibarra11
    @aibarra11 3 роки тому +6

    for the first optimization, there is also ->when for eloquent queries. No need to write out IF statements

  • @pamithbosilu6055
    @pamithbosilu6055 3 роки тому

    Laravel Tips and Tricks - ua-cam.com/video/kvlGWqra_rc/v-deo.html

  • @randomguy5922
    @randomguy5922 4 роки тому

    Very useful things..........i almost know all of them but its surely some parts where new. Thanks

  • @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.

  • @gergelygrusz713
    @gergelygrusz713 Рік тому

    This is brilliant, thank you!

  • @sebastianromerolaguna7408
    @sebastianromerolaguna7408 3 роки тому

    Have you think in do an tutorial explaining queries for statistics. I haven seen videos about!.
    Have a good day

  • @javieru5871
    @javieru5871 2 роки тому +1

    I think for tip 4, we can also use withCount from Lavaravel 5.2.32 or higher.

  • @simbarashemaunga5575
    @simbarashemaunga5575 Рік тому

    This was an amazing tutorial!

  • @etokafrancis5700
    @etokafrancis5700 4 роки тому +1

    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

  • @brokoli5797
    @brokoli5797 3 роки тому

    Great tips! saved my time so much.

  • @jecoy9413
    @jecoy9413 4 роки тому +1

    what text editor are you using ?

  • @DANJ93Mort
    @DANJ93Mort 7 днів тому

    Nice job, thanks

  • @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 ...

  • @sayedahmadnaweed1
    @sayedahmadnaweed1 2 роки тому

    You are amazing. Thank you

  • @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?

  • @197syahnur
    @197syahnur 4 роки тому

    tip 2 is super brand new to me! Thankss

  • @jailsoncarneiro4936
    @jailsoncarneiro4936 3 роки тому

    Great Job! Thanks a lot!

  • @JohnnyBigodes
    @JohnnyBigodes 4 роки тому

    And another great and useful examples. Thank you

  • @guilhermemoraes4055
    @guilhermemoraes4055 3 роки тому +1

    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.

  • @pankajbokdia
    @pankajbokdia 2 роки тому

    Super helpful!

  • @sebastianromerolaguna7408
    @sebastianromerolaguna7408 3 роки тому

    Thanks, it help me.

  • @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?

  • @arty4
    @arty4 3 роки тому

    For tip 1 u can use ->when($expr, $callback) function

  • @lawrencediokno4883
    @lawrencediokno4883 2 роки тому

    how are you formatting your return data to look like that?

  • @Chitte011
    @Chitte011 3 роки тому

    You are awesome man, great respect for you! (y)

  • @androidbornofficial5148
    @androidbornofficial5148 4 роки тому

    Amazing video. Please make video
    Vue js pagination with later with filter queue string.

  • @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 роки тому +1

      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 роки тому +2

      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()"

  • @sretksor8689
    @sretksor8689 2 роки тому

    what is the name of IDE that you using in video?

  • @rizkihutama5633
    @rizkihutama5633 3 роки тому

    do you have a video that store json text to database, i'm still strugling with that?

  • @namachivaaya
    @namachivaaya 4 роки тому

    Nice tips 👍👍👍

  • @mikevazovsky9211
    @mikevazovsky9211 3 роки тому +1

    Good!

  • @hariharan-wt6qk
    @hariharan-wt6qk 3 роки тому +1

    Thanks a lot❤️

  • @ehSamurai3483
    @ehSamurai3483 3 роки тому

    In the first tip what is ::query() method?

  • @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

  • @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!

  • @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.

  • @mastago3226
    @mastago3226 4 роки тому

    thank you Andrew

  • @emadaldeenmukhtar
    @emadaldeenmukhtar 4 роки тому

    perfect bro, keep it up

  • @indeveloperid6061
    @indeveloperid6061 4 роки тому

    Why we have to write like "uri" or "action" at route code ?

  • @truongpm2144
    @truongpm2144 Рік тому

    amazing !!!!

  • @DRMOHAMEDKHDR
    @DRMOHAMEDKHDR 3 роки тому

    Thanks alot

  • @davidmucioca6423
    @davidmucioca6423 4 роки тому

    Very helpful

  • @joepalala4757
    @joepalala4757 Рік тому

    Another tip, You can now use ->latest() in your queries which will getlatest by created date (afaik)

  • @sheenismhaellim2215
    @sheenismhaellim2215 4 роки тому

    How does the object $poperties know what table to query just by initializing it with Property::query()?

    • @wsqplm
      @wsqplm 4 роки тому

      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.

  • @johnmarkenriquez8808
    @johnmarkenriquez8808 4 роки тому

    Super helpful..

  • @sudheertripathi3882
    @sudheertripathi3882 2 роки тому

    tip3 is fire

  • @paulmimicry9147
    @paulmimicry9147 4 роки тому

    How about the amount of query executed?

  • @carlosfranciscobenegasbini78
    @carlosfranciscobenegasbini78 3 роки тому

    Amazinng!

  • @naungyehtet1231
    @naungyehtet1231 2 роки тому

    Subscribed

  • @loremipsum5642
    @loremipsum5642 3 роки тому

    Hi, can you provide a github repo for this?

  • @silvesterwali6565
    @silvesterwali6565 3 роки тому

    i love this

  • @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!

  • @grayaahammed917
    @grayaahammed917 4 роки тому

    What IDE is used in this video please ?

    • @gobanq
      @gobanq 3 роки тому

      It’s phpstorm

  • @josegerardosanchezalvarado4703
    @josegerardosanchezalvarado4703 2 роки тому

    esto me salvo la vida User::whereHas('model', function ($query) {
    $query->where('propiedad', '!=', 'value');
    })->with(['model', 'model'])->get();

  • @ethanj1533
    @ethanj1533 4 роки тому

    What ide is that?

  • @asim-gandu-phenchod
    @asim-gandu-phenchod 3 роки тому

    Diamond content

  • @Arman-cn2tf
    @Arman-cn2tf 4 роки тому

    Great

  • @davidspooner4684
    @davidspooner4684 3 роки тому

    Way too many commercials interrupting this tutorial. Hard to follow with so many interruptions.

    • @aschmelyun
      @aschmelyun  3 роки тому +1

      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 3 роки тому

    Говнокодик конечно… есть ощущение, что только программисты из СНГ заботятся о качестве кода.

  • @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.

  • @pamithbosilu6055
    @pamithbosilu6055 3 роки тому

    Laravel Tips and Tricks - ua-cam.com/video/kvlGWqra_rc/v-deo.html