Laravel Routing

0
213

The basic routes are defined in the app directory under the name ‘routes.php’.

Basic Routing

The basic routing is responsible for routing all your requests to the respective controller. Below are the several general syntaxes for the basic routing.

GET Route

Route: :get(‘/’, function()

{

return ‘Hello World’;

});

POST Route

Route: :post(‘foo/bar’, function()

{

return ‘Hello World’;

});

Route Registration for Multiple Verbs

Route: :match(array(‘GET’, ‘POST’), ‘/’, function()

{

return ‘Hello World’;

});

Route Registration Responding to Http Verb

Route::any(‘foo’, function()

{

return ‘Hello World’;

});

Forcing A Route To Be Served Over HTTPS

Route::get(‘foo’, array(‘https’, function()

{

return ‘Must be over HTTPS’;

}));

And if in any condition, you would require generating URLs to your routes then you can use the following command.

$url = URL::to(‘foo’);

Also Read: Laravel Configuration

Understanding Routing Mechanism

Take a look at the following image to understand the basic mechanism behind the routing.

Step 1: Identify the type of request and execute the root URL to get the appropriate outcome.

Step 2: The syntax itself suggests the destination of the request. The executed URL matches itself with the appropriate method present under the file name route.php. But, in this above instance, the URL will get a match under the root (/) directory. The associated function will be evoked and executed.

Step 3: Now it’s the turn of the function that is to be executed. The function will call the template file hello.php. The function is calling for the view() function with an argument ‘hello’.

Routing Parameters

If you want to capture the parameters passed in the URL then you will be requiring the change the codes in routes.php. There are two types of passing the parameters in a given URL.

* Required parameters

The parameters need to be strictly present in the URL.

Route::get(‘ID/{id}’,function($id)

{

echo ‘ID: ‘.$id;

});

* Optional parameters

There are several parameters which might not require being present in the URL. For this kind of routing parameter, use the following syntax.

Route::get(‘/user/{name?}’,function($name = ‘xyz’)

{

echo “Name: “.$name;

});