Press "Enter" to skip to content

Route binding, Type hinting and Clean coding – Laravel

Now, watch carefully. This is how it’s done.

Step 1: In your route file web.php

Step 2: In your Service provider (probably RouteSeviceProvider.php)

Step 3: Finally in your controller (BookController.php)

Step 4: Now, in your view file,

Explanation

This single form is able to handle both of your new books and updates an old book scenario.

If you hit route book/create, you will get a form to create a new book. The controller would receive a new instance of Book model and it would be saved.

If you hit route book/1, you will get a form to update the book with ID of 1. Here, Controller would receive the instance of Book but this time, a book of ID 1 has been retrieved.

If you hit route book/{something}, you will have a 404 error(because it does not exists).

Keep in mind, that this idea is only tested in Laravel 5.6. Check this post to know more about Laravel 5.6.

 

Everything is awesome.

Be First to Comment

    Leave a Reply

    Your email address will not be published.