article

Thursday, July 7, 2016

Laravel - Routing

Laravel - Routing

Basic RoutingBasic routing is meant to route your request to an appropriate controller. The routes of the application can be defined in app/Http/routes.php file.

Example
app/Http/routes.php


 
Route::get('/', function () {
   return view('welcome');
});
resources/view/welcome.blade.php
<!DOCTYPE html>
<html>
   
   <head>
      <title>Laravel</title>
      <link href = "https://fonts.googleapis.com/css?family=Lato:100" rel = "stylesheet" 
         type = "text/css">
      
      <style>
         html, body {
            height: 100%;
         }
         body {
            margin: 0;
            padding: 0;
            width: 100%;
            display: table;
            font-weight: 100;
            font-family: 'Lato';
         }
         .container {
            text-align: center;
            display: table-cell;
            vertical-align: middle;
         }
         .content {
            text-align: center;
            display: inline-block;
         }
         .title {
            font-size: 96px;
         }
      </style>
   </head>
   
   <body>
      <div class = "container">
         
         <div class = "content">
            <div class = "title">Laravel 5</div>
         </div>
   
      </div>
   </body>

</html>
Step 1 − First, we need to execute the root URL of the application.

Step 2 − The executed URL will match with the appropriate method in the route.php file. In our case, it will match to get the method and the root (‘/’) URL. This will execute the related function.

Step 3 − The function calls the template file resources/views/welcome.blade.php. The function later calls the view() function with argument ‘welcome’ without using the blade.php. It will produce the following HTML output.

Routing Parameters 
 
<?php
// First Route method – Root URL will match this method
Route::get('/', function () {
   return view('welcome');
});

// Second Route method – Root URL with ID will match this method
Route::get('ID/{id}',function($id){
   echo 'ID: '.$id;
});

// Third Route method – Root URL with or without name will match this method
Route::get('/user/{name?}',function($name = 'Virat Gandhi'){
   echo "Name: ".$name;
});

Here, we have defined 3 routes with get methods for different purposes. If we execute the below URL then it will execute the first method.

http://localhost:8000

If we execute the below URL, it will execute the 2nd method and the argument/parameter ID will be passed to the variable $id.

http://localhost:8000/ID/5

After successful execution of the URL, you will receive the following output − ID: 5

If we execute the below URL, it will execute the 3rd method and the optional argument/parameter name will be passed to the variable $name.

http://localhost:8000/user/tutorial101

After successful execution of the URL, you will receive the following output −  Name: tutorial101

Related Post