Laravel Route Model Binding: All You Need To Know

Поделиться
HTML-код
  • Опубликовано: 2 окт 2024

Комментарии • 96

  • @rossco5551
    @rossco5551 3 года назад +12

    Perfect content. This is almost assumed knowledge, but it's not something I ever came across when first delving into Laravel. Consequently I learned by osmosis which isn't ideal. I know you'll solve this problem for others with your new learning roadmap. Great stuff.

  • @rahulraveendran9520
    @rahulraveendran9520 3 года назад +6

    Great video. The missing method and changing route key for a specific route was new information for me. Thanks

  • @ZhanOmar
    @ZhanOmar 2 года назад +1

    Is there any solutions for route model binding with hasMany relationships? If a user has many products, auth()->user()->products()->findOrFail($product) works fine, but with route model binding, user can get access to other products. Middleware checking will create an extra load (double DB request).

    • @ZhanOmar
      @ZhanOmar 2 года назад

      something like with scopes but not.
      Route HasMany binding for auth()->user()->products()->findOrFail($product);

  • @tradewithtony
    @tradewithtony 3 года назад +3

    Great content as always, the missing method it's a magic. I'm following your channel quite well from Africa/Dar es salaam. Keep up Good work

  • @ironspider9026
    @ironspider9026 3 года назад

    Excellent info thanks for sharing.

  • @ClawHammer23
    @ClawHammer23 3 года назад

    Great video Povilas, Thanks

  • @martinh4982
    @martinh4982 3 года назад +2

    Today I am extremely happy... IT have upgraded our LTS server to the latest SP which includes PHP 7.4, so I can finally start playing around with Laravel 8! Oh, and nice vid Povilas as always!

  • @rolandosanches2344
    @rolandosanches2344 3 года назад +2

    php artisan make:controller CategoryController --resource --model=Category can be shorted for php artisan make:controller CategoryController -r -m Category

  • @GergelyCsermely
    @GergelyCsermely 3 года назад

    Thanks

  • @belce1982
    @belce1982 3 года назад

    Thanks, keep going!

  • @ravaliyanikunj
    @ravaliyanikunj 3 года назад +1

    is the capital Email and Password affect in attempt method in laravel i add field name in camalcase in database.
    if(Auth:: attempt (['Email'=>$request->email,'Password'=>$request->password]))
    this will return always false if i used Email and Password instead of email and password.
    can you tell me why this happening??

  • @ALiHameedAlHashemi
    @ALiHameedAlHashemi 3 года назад

    super perfect content

  • @steeyns8482
    @steeyns8482 3 года назад

    Thank you so much

  • @msdeav
    @msdeav 3 года назад

    Thank you, sir...

  • @crispy-channel
    @crispy-channel Год назад

    what if i need to add another condition like created_by = auth()->user()

  • @mohammadashrafuddinferdous8649
    @mohammadashrafuddinferdous8649 2 года назад

    Before watching the video: php reflection api is powerful enough.

  • @ggmm7463
    @ggmm7463 2 года назад

    i need show info , table product and category ,union how whit model binding?

  • @manto7
    @manto7 2 года назад

    Putting a resource controller inside grouped routes is not working

  • @orpheusohms
    @orpheusohms 3 года назад +1

    One more thing to add. If you want to bind a resource, nested resource or any route, you can you use scope as well. You can use it when you have multiple route model binding and you don't need to use the getRouteKeyName function

  • @NotBeHaris
    @NotBeHaris 3 года назад +1

    Sir awesome knowledge which you are sharing with us. Thanks for this. Sir i have question that what is alternative of id in url. And is it safe to show id in url.

    • @LaravelDaily
      @LaravelDaily  3 года назад

      Alternative is UUID.
      Examples: laravelexamples.com/tag/ramsey-uuid
      Old video: ruclips.net/video/TRDu1crA-g0/видео.html

  • @LippittDesigns
    @LippittDesigns Год назад

    Is it possible to cache the eloquent model?

  • @ChangeYourLifeForever
    @ChangeYourLifeForever Год назад

    i finish the LEVEL 1 and I am doing NOW the LEVEL 2 and this improve a lot my level THANK YOU SO MUCH

  • @bmtamim7818
    @bmtamim7818 3 года назад +1

    Thanks, for this awesome video.

  • @krunalshrimali4471
    @krunalshrimali4471 3 года назад +2

    Does the route model binding check policies or gates?

  • @poplach
    @poplach 3 года назад

    didn't know about 'missing'

  • @bidhanbaniya7605
    @bidhanbaniya7605 3 года назад +1

    While using laraveldaily invoice package it is throwing me an error saying target class [ ] doesn't exist how to solve this?

    • @LaravelDaily
      @LaravelDaily  3 года назад

      Open an issue on Github, with the exact code you've written, then one of my teammates may find time to help.

  • @abdulrahman-ej7me
    @abdulrahman-ej7me 3 года назад +1

    Please, put this lessons in a category

  • @surflaweb
    @surflaweb 3 года назад

    Great

  • @guilhermemoraes4055
    @guilhermemoraes4055 3 года назад +1

    5:25 Can I get data using more than one database row? For example, id OR slug to bring the same result?

    • @LaravelDaily
      @LaravelDaily  3 года назад +2

      This is part of the docs that describe this behavior: laravel.com/docs/8.x/routing#customizing-the-resolution-logic

    • @ivanjelenic5627
      @ivanjelenic5627 3 года назад +1

      You can probably do something like this:
      Route::get('/resource/{id_or_slug}', function ($id_or_slug) {
      $isId = ctype_digit($id_or_slug);
      if ($isId) { // find as id
      return Resource::findOrFail($id_or_slug);
      }
      else // find as slug
      {
      return Resource::where('slug', '=', $id_or_slug)->firstOrFail();
      }
      });
      There might be easier ways to do it...
      One problem with this is if there's a slug name that consists of only digits it will hit the route as id, not as a slug. In this case I guess you should add a validation rule that disallows slug names that are only numeric, when you're creating the resource - or change the slug to something.

  • @emmanuels.emokor3783
    @emmanuels.emokor3783 3 года назад

    I use this method a lot. However, I encountered an issue ModelNotFoundException error: No query results for the model. I don't know what went wrong yet I implemented the same thing in other parts of the application and it works very well. I get the error on my edit resource. I can't find what went wrong

  • @noshit_isreal
    @noshit_isreal 3 года назад

    Sir i have question . how to create rule validation array 2d [ [true,"10:00","11:00"],[false,"",""]] when true index[1][2] need some value , false don't need some value. sorry im bad english

  • @adampatterson
    @adampatterson 2 года назад

    Is it possible to Bind multiple?
    /category/{category:slug}/{sub_category:slug}
    my controller method: __invoke(Category $category, Category $sub_category)
    But I end up wit than error "App\Models\Category::subCategories()"
    The error is fixed with Route::bind but i'd love to know if it's possible without.

    • @LaravelDaily
      @LaravelDaily  2 года назад +1

      You probably need to have hasMany relationship in Category called exactly subCategories()
      Read this part of the docs: laravel.com/docs/9.x/routing#implicit-model-binding-scoping

    • @adampatterson
      @adampatterson 2 года назад

      @@LaravelDaily That worked, but I also realized that subcategory slugs are not unique so I had to manually query anyway.

  • @mohammadkhazaee9730
    @mohammadkhazaee9730 3 года назад

    Interesting

  • @mohamedsalem9889
    @mohamedsalem9889 6 месяцев назад

    thanks

  • @nandkishor-gi8or
    @nandkishor-gi8or 3 года назад

    How can we load relationship data in route model binding scenario.

    • @LaravelDaily
      @LaravelDaily  3 года назад

      See this post: ruclips.net/user/postUgwq5jJmPqxjwPTdmr14AaABCQ

  • @maysonhori
    @maysonhori 3 года назад

    I love u

  • @jagrutivaru5827
    @jagrutivaru5827 3 года назад

    Hi
    I have tried route building and see the query in laravel debugger it's making query select * from products where slug = product-1, how can I select specific columns only for example I only want 3 filed to show and want to select that particular fields only. Can we do so?

  • @sadiriy
    @sadiriy 2 года назад

    I was looking for how to change the route key, and you showed it, although it was the tiny unnecessary thing that either everybody knows well or nobody needs at all. Liked and subscribed at that moment :) Thank You!

  • @aymenmohammed2625
    @aymenmohammed2625 3 года назад

  • @yukikteez8036
    @yukikteez8036 2 года назад

    Hey, In my model I have a pivot data type array, how I can perform cats on it ?

  • @JerryJonesIndia
    @JerryJonesIndia Год назад

    Sir, how to solve the compact() string or array error in laravel 8 with php version 8.x. I recently came across this error but nowhere in internet found the solution. So I have to downgrade the php version to 7.x

    • @LaravelDaily
      @LaravelDaily  Год назад +1

      Can you show the exact error? I haven't seen any errors with compact and php 8

    • @JerryJonesIndia
      @JerryJonesIndia Год назад

      @@LaravelDaily Sir this was the error:
      "ErrorException compact(): Argument #1 must be string or array of strings...."
      After I downgraded, it was resolved, though. But what if I want to keep php v 8.x?

    • @LaravelDaily
      @LaravelDaily  Год назад

      Hard to comment without knowing what you actually passed into that compact(). Could you show the full code? Maybe you just passed null or non-existing variable?

  • @aparnasajith3532
    @aparnasajith3532 3 года назад

    Hi,
    I got 404 error after submitting the login form in laravel 8 auth.
    Once I registered with a new user it directly go to the dashboard and shows 404 error. When I remove that user from DB I am able to get the login page.
    So everytime when a user register it goes to dashboard and shows 404. error. That means, if there is no data in DB it will work.
    Please help me. I am new to this laravel. And I got stuck here

    • @LaravelDaily
      @LaravelDaily  3 года назад

      Sorry I can't help you without debugging full code of your project, so can't answer in a RUclips comment.

  • @helderneves91
    @helderneves91 3 года назад

    It's good to use but I think we can't use eager loading using show(Product $product)... I prefer to pass the $product_id and do $product = Product::with('category')->findOrFail($product_id)->get()...

    • @Michielofzo
      @Michielofzo 3 года назад +1

      you can use $product->load('category') in your controller function.

    • @daleryanaldover6545
      @daleryanaldover6545 3 года назад +1

      Just to add context, route model binding only gets the model without relationship by default so we would not be able to use with() in this case, rather use load() method which works because load() is used to load relationship after the parent model has been queried.

  • @redeyesgaming2901
    @redeyesgaming2901 3 года назад

    First view first like ♥️♥️♥️♥️

  • @couldbejake
    @couldbejake 2 года назад

    what IDE is that?

  • @goodfellow4353
    @goodfellow4353 11 месяцев назад

    if my slug looks like "/some/my/url"/ how do i can find model?

    • @LaravelDaily
      @LaravelDaily  11 месяцев назад

      I wouldn't advise to use "/" in slugs cause then it's very confusing, and your question is a proof of it.

    • @goodfellow4353
      @goodfellow4353 11 месяцев назад

      @@LaravelDaily ty, i'll but not in this project((

    • @goodfellow4353
      @goodfellow4353 10 месяцев назад

      Route::get('/search/{search}', function (string $search) {
      return $search;
      })->where('search', '.*');

  • @leonun
    @leonun 3 года назад

    very helpfull thanks!

  • @kelvezu1585
    @kelvezu1585 3 года назад

    Thanks for your daily tips.

  • @abdul-rehman
    @abdul-rehman 3 года назад

    Povilas, please create a video on using UUIDs instead of IDs in the database. I watched that video you uploaded but it is too old. And I think Laravel now supports UUIDs internally so that we don't need to use external packages. And can we only use UUID in the database table (without ID)?

    • @LaravelDaily
      @LaravelDaily  3 года назад +1

      There will be some "surprise" related to UUIDs tomorrow on the channel :)

    • @abdul-rehman
      @abdul-rehman 3 года назад

      @@LaravelDaily ThankYou so much sir! You are doing great.

  • @JamesAutoDude
    @JamesAutoDude Год назад

    Can you do this with services?

    • @LaravelDaily
      @LaravelDaily  Год назад

      Depends on what you mean by "this". You can always try and see if it works.

    • @JamesAutoDude
      @JamesAutoDude Год назад

      @@LaravelDaily I mean using model binding but having a service as well that processes more things like where clauses

  • @alexisarcegomez8698
    @alexisarcegomez8698 3 года назад

    Awesome content, I didn't know most of the details described on this video. I have a question, any help would be appreciated, is there any way to use route model binding with collection instead of single model? I'm trying to implement this feature with livewire in a project but I haven't any success yet😥

    • @JamesAutoDude
      @JamesAutoDude Год назад

      Yeah you specify it like normal:
      function functionName(Model $model)
      Then you break it down like:
      $model->where(conditions)->get()
      Or even just:
      $model->get()
      If your relationships are setup right
      Or, I believe you can just pass it to the view (if you need the collection in blade) and just put it directly like:
      return view('pages.page', [ 'model' => $model ]);
      Then in your blade you just do:
      Foreach ($model as $data)
      $data->name
      Endforeach

  • @sumanthapa7161
    @sumanthapa7161 3 года назад

    Thanks for the great video

  • @JY-xv7ic
    @JY-xv7ic 3 года назад

    is this work on lumen?

  • @bubblesort6368
    @bubblesort6368 3 года назад

    Looks very magically and I am not sure that is good...

    • @infureal
      @infureal 3 года назад

      That is not "magic". I wrote comment for better explonation

  • @muhmmadusmananwar2037
    @muhmmadusmananwar2037 Год назад

    Real Gem of Laravel ❤

  • @netconsole2832
    @netconsole2832 3 года назад

    awesome tutorial

  • @JoshuaMusau
    @JoshuaMusau 2 года назад

    love it, thanks

  • @ismoilkirgizov1640
    @ismoilkirgizov1640 3 года назад

    excellent content

  • @fftfaisal
    @fftfaisal 3 года назад

    HI. I am a daily viewer of your channel. I am using your roles and permission system on my project. but I am using multi auth using guard for the separate user and admin session. Because I don't want to login as admin in the user front end. everything is fine. but it giving forbidden error with gate::denies() in the controller. I think it is coming for a guard. How do I check gate ability with auth guard ?? any method for it? or a different method for verifying this situation?

    • @LaravelDaily
      @LaravelDaily  3 года назад +1

      I don't actively work with multi guards so can't advice. And that is the exact reason why I don't work with multi guards, because it's hard to solve situations like the one you described.

    • @fftfaisal
      @fftfaisal 3 года назад

      @@LaravelDaily thanks for your reply

    • @LaravelDaily
      @LaravelDaily  3 года назад +1

      I use roles/permissions for things like that. With different Gates or Middlewares. For my general approach, see video: ruclips.net/video/kZOgH3-0Bko/видео.html

  • @poofick
    @poofick 3 года назад

    "... Laravel will magically find ... so how does it all work? ..." - didn't get an answer after watching this video :(

    • @rahulxcr
      @rahulxcr 3 года назад

      Internally it will be same as findOrFail model with the passed parameter. Hope this helps.

    • @LaravelDaily
      @LaravelDaily  3 года назад +2

      I didn't think it was useful in practice for people to know what's under the hood, as they are not likely to change framework internals, but if you wanna know - here, I've googled an article 100r0bh.medium.com/demistifying-route-model-binding-in-laravel-a6e27e5a458e

    • @poofick
      @poofick 3 года назад

      @@LaravelDaily cool, thanks, that article clarified things a bit. So basically it's some "magic" methods for Resource controllers and in models which do all the work for you, and as you mentioned in your video you can overwrite them. Also at first I got it confused with Service Container logic which made me write the original comment.
      p.s. thanks for all the videos you make!

  • @user85937
    @user85937 3 года назад

    Well explained, I didn't know about the missing() function yet on routes. Hope you will get the 100k subscribers but I think you will need to extend your content to different languages and frameworks as the PHP market share has been in decline for a couple of years now. To put things in perspective, you already have more subscribers than the Laravel subreddit has so I doubt there is much more growth to gain.

    • @oluchukwuughagwu8293
      @oluchukwuughagwu8293 Год назад

      I’m glad he didn’t listen to your advice. People like us appreciate his consistency in Laravel