Laravel Basic RoutingRouting is one of the essential concepts in Laravel. The main functionality of the routes is to route all your application requests to the appropriate controller. Default Route filesAll Laravel routes are defined inside the route files located in the routes directory. When we create a project, then a route directory is created inside the project. The route/web.php directory contains the definition of route files for your web interface. The routes in web.php are assigned with the web middleware group that provides the features like session state and CSRF protection. The routes defined in routes/api.php are assigned with the API middleware group, and they are stateless. We will start by defining the routes in routes/web.api file. The routes defined in the routes/web.php can be accessed by entering the defined URL to the browser. Let's understand this through an example. The definition of default route files. In the above case, Route is the class which defines the static method get(). The get() method contains the parameters '/' and function() closure. The '/' defines the root directory and function() defines the functionality of the get() method. In the above route, the url is '/'; therefore, we entered the localhost/laravelproject/public URL in the web browser. Output: As the method returns the view('welcome'), so the above output shows the welcome view of the Laravel. Let's see another example. Now, we provide another url in this example. In the above example, the route is defined in which URL is '/example', so we need to enter the URL "localhost/laravelproject/public/example" in the web browser. Output: CSRF ProtectionThe HTML forms that are pointing to Post, Put or Delete routes defined in the web route files should include CSRF token field. If the CSRF token field is not included, then the request will be rejected. The router defines the routes that can respond to the following http verbs: Route::get($uri, $callback); Route::post($uri, $callback); Route::put($uri, $callback); Route::patch($uri, $callback); Route::delete($uri, $callback); Route::options($uri, $callback); Sometimes the situation arises when you need to register a route that responds to the multiple http verbs, and this can be achieved by using the match() method. Sometimes you want to register a node that responds to all the http verbs, so we use any() method. Two most commonly used route methods are:
Second way is to access the redirect() method directly. In the above cases, both the routes are navigating from /hello to the root directory, i.e., '/'.
Next TopicLaravel Routing Parameters |