Controller, Route in Laravel

Tram Ho

Introduce

  • In the MVC model, the C – Controller specializes in handling the logic for user requests.
  • When you go to a certain website, for example code.itzone.asia , you have sent a request to a Controller so that it takes you to the interface of that website.

Controller

1. Create a controller

  • In laravel, to create a controller, you use the command:

  • Result:

  • Here you can define functions to handle the logic you want.
  • But how should it be defined? What should be defined here?
  • Then here is an example:

  • When you declare a function as index , by default when you call this controller function index will be run.
  • In addition to the index , there is also a function that will run by default when you call the controller __invoke :

  • To have this function you just need to add the option –invokable when creating the controller:

2. Resource Controllers

  • Similar to normal Controller but when you create Resource Controllers , you will get the available functions index, create, show, edit, update, delete

  • That is why the resource controller is very useful when you need to CRUD a certain resource. In addition, when declaring the resource controller, you do not need to create each path to each function, just use the resource .

Routes

  • Once you have the controller , of course there must be something to lead there. Looking at the title, you already know what it is.
  • To declare routes , you need the routes . directory

image.png

  • Here you will see 4 files but you only need to pay attention to 2 files api.php and web.php .
  • With api.php you will define the api here. And web.php to define the routes on the web path.

1. Methods in Routes

  • In laravel support methods:

  • Where $url: route path and $callback : is an action to be performed.

2. Optional parameter

  • You can also pass parameters in the URL by placing them between {} :

  • Of course you can also pass multiple parameters on a URL, not just one:

3. resource routes

  • As mentioned above in the controller section, its effect is very simple, instead of you having to declare a bunch of routes , you just need to declare 1 routes for all of them:

  • You will get the respective routes:

image.png

4. Route name

  • As you can see above the image has a column of route name , then to declare the name of a route, you just need to:

5. Group routes

  • You can group multiple routes with similar behavior into one group:

  • Wall:

  • Of course, the same Controller is fine.

Conclusion

  • This article introduces you to the basics of creating a controller and how to call that controller via routes .
  • Hope they will be of help to everyone.
Share the news now

Source : Viblo