Laravel 8 Tutorial - Laravel Routing

Published January 29, 2022

In Laravel, the routing concept is very important. It allows Laravel to route all the application requests to the appropriate controller. In this chapter, we'll learn more about the routing concept in Laravel apps.

We'll take a look at:

  • How to Make a Route in Laravel

  • Laravel's routing techniques

  • The Routing Parameters

1. How to create Routes in Laravel

Application route files are defined in the app/Http/routes.php file. To create routes in Laravel, you need to define them in the route files in the route sub-directory. These route files will be generated by Laravel and loaded automatically

Route:: get ('/', function () {

   return 'an Action here';

});

 

Example

The following route opens  the welcome page in the http://localhost/app/dashboard

Route:: post('user/dashboard', function () {

   return 'Welcome to dashboard';

});

 

2. The Routing mechanisms in Laravel

There are three main steps to routing an application in Laravel:

  • Step 1: First, Create a root URL for your Laravel application, and then run it

  • Step 2: To execute all the related functions, ensure that your URL exactly matches the method defined in the root.php file.

  • Step 3: Finally, the function calls the template files. This function will call the view() function using the file name from the resources/views/ without including blade.php.

Example

App/Http/routes.php

<?php

Route:: get ('/', function () {

   return view('laravel');

});

 

Resources/view/laravel.blade.php

<html>

<head>

   <title>Laravel8 Tutorial</title>

</head>

<body>

   <h2>Laravel8 Routing</h2>

   <p>Welcome to Laravel8 Routing</p>

</body>

</html>

 

3. The Routing Parameters

Occasionally, while developing a Laravel app, you may need to capture the parameters sent ahead using a URL. Laravel 8 provides two methods for capturing the passed parameters:

  • Optional Parameters

  • Required Parameters 

 

a) Optional Parameters

Some parameters in the URL are temporal, yet developers need to use them. Such parameters are usually denoted with a question mark symbol preceded by the name of the parameter.

Example:

This example shows an example of an optional parameter

 

Route :: get ('emp/{name?}', function ($name = 'Woolan') {

    echo $name;

});

 

b) Required Parameters

Occasionally, you may need to work with a URL segment in your project. We encapsulate our route parameters within the curly braces with the alphabets inside to capture our selected segment.

Example

Let’s capture the user id in the following example

 

Route :: get ('user/{id}', function ($id) {

    echo 'User '.$id;

});

 

 

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

223 Views