Laravel 5.4 Tutorial Part-5: Laravel Routing with Views & Controller

What is View?

Views hold the presentation logic of a Laravel application. Views contain the HTML served by your application and separate your controlleer. Application logic from your presentation logic. Views are stored in the resources/views directory. You can show your view page from route directly. A simple view might look something like this:

<html>
<body>
   <h1><h1>Hello, World</h1>
</body>
</html>

Show html Page in Routes from Laravel views folder

Finally now we’ll understand how to see the simple html page with the help of routing.

just update your root method in routs/web.php as like


Route::get('/', function () {
return view('hello');
});

And Now create a simple html Page called “hello.php” as like:


<!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>

call html page from view folder in laravel routes

call html page from view folder in laravel routes

Passing Data From Route to Views

While building application it may be required to pass data to the views. Pass an array to view helper function. After passing an array, we can use the key to get the value of that key in the HTML file.

Step 1 − Add the following line in routes/web.php file to set the route for the above view.

Route::get('/test', function(){
 return view('test',['name'=>'Masud Alam']);
});

Step 2 − The value of the key name will be passed to test.php file and $name will be replaced by that value.

Step 3 − Now Copy the following code and save it at resources/views/test.php

<html>
   <body>
      <h1>Welcome <?=$name;?>!</h1>
   </body>
</html>

Step 4 − Visit the following URL to see the output of the view.

http://localhost:8000/test

Step 5 − The output will appear as shown in the following image.

Laravel Route and View Output

Laravel Route and View Output

What is Controller:

In MVC framework, the letter “C” stands for Controller. In Laravel, Controllers is responsible for controlling the application logic and acts as the coordinator between the View and the Model. The Controllers receives input from users via the View, then process the user’s data with the help of Model and passing the results back to the View.

Creating Controllers:

In Laravel PHP Framework we can create Controllers for easy using the ‘Artisan’ CLI (Command Line Interface).


php artisan make:controller homeController

Create Laravel Controller

Create Laravel Controllers

Default Controllers will be place at app\Http\Controllers. You can see that basic source code of the ‘homeController.php‘.

<?php
namespace test\Http\Controllers;

use Illuminate\Http\Request;

use test\Http\Requests;

class homeController extends Controller
{
    //
}

Calling Controllers from Routes

The Controllers is called from routes.php that placed at app\Http\routes.php. Here’s simple syntax from the routes.php file :


Route::get('/', [email protected]');

if users enter the base Url “/” that will call the “homeController.php” at the “index” method.

Creating View:

Now create home.php file in resources\views\ folder like this example

<!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">Welcome</div>
         /<div>
			
      </div>
   </body>

</html>

Calling View File in homeController

Add index functions and Call View File into homeController.php like this examples

<?php
namespace test\Http\Controllers;

use Illuminate\Http\Request;

use test\Http\Requests;

class homeController extends Controller
{
    //
    public function index(){

    	return view('home');

    }
} 

Now, you can execute “http://localhost:8000” url in your browser, and you’ll get output as like:

Laravel Controller and View Output

Laravel Controllers and View Output

Passing Data from controllers to View

Sometimes we need to pass data from controllers to view in laravel. There are many ways to send or pass data to view from controllers. I am describing some easy way how to pass data form controllers to view in laravel.

Suppose you wanted to pass the name of a list into the home page view. Open the Home controller (app/Http/Controllers/homeController.php) and corresponding view (resources/views/home.php). Modify the Home controller’s index action to look like this:

<?php

namespace test\Http\Controllers;

use Illuminate\Http\Request;

use test\Http\Requests;

class homeController extends Controller
{
    //
    public function index(){

    	return view('home',["name"=>"Masud Alam"]);

    }
}

Now Modify your home.php file in resources\views\ folder like this example

<!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: 36px;
         }
      </style>
   </head>
   
   <body>
      <div class = "container">
         
         <div class = "content">
            <div class = "title">Welcome <?=$name;?></div>
         </div>
			
      </div>
   </body>

</html>

Now, you can execute “http://localhost:8000” url in your browser, and you’ll get output as like:

Passing Data From Controller to view

Passing Data From Controller to view

When passing information in this manner, $data should be an array with key/value pairs. Inside your view, you can then access each value using its corresponding key, such as . As an alternative to passing a complete array of data to the view helper function, you may use the with method to add individual pieces of data to the view:

<?php

namespace test\Http\Controllers;

use Illuminate\Http\Request;

use test\Http\Requests;

class homeController extends Controller
{
    //
    public function index(){

    	return view('home')->with('name', 'Masud Alam');;

    }
}

You can also use a cool shortcut known as a magic method to identify the variable name:

<?php

namespace test\Http\Controllers;

use Illuminate\Http\Request;

use test\Http\Requests;

class homeController extends Controller
{
    //
    public function index(){
    	$name = 'Masud Alam';
    	return view('home')->withName($name);

    }
}

You can use the with method to pass multiple variables into a view. Just pass along an associative array, as demonstrated here:

<?php

namespace test\Http\Controllers;

use Illuminate\Http\Request;

use test\Http\Requests;

class homeController extends Controller
{
    //
    public function index(){
    	 $data = array('name' => 'Masud Alam','date' => date('Y-m-d')); 
    	return view('home')->with($data);

    }
}

To view both the $name and $date variables within the view, update your view to include the following:

You last visited  on <?=$date;?>
Passing Array Data From Controller to view

Passing Array Data From Controller to view

You could also use multiple with methods, like so:

<?php

namespace test\Http\Controllers;

use Illuminate\Http\Request;

use test\Http\Requests;

class homeController extends Controller
{
    //
    public function index(){
    	return view('home')->with('name', 'Masud Alam')
  			        ->with('date', date('Y-m-d'));

    }
}

This approach can get messy if you needed to pass along more than two variables. Save some typing and your eyesight using PHP’s compact() function:

<?php

namespace test\Http\Controllers;

use Illuminate\Http\Request;

use test\Http\Requests;

class homeController extends Controller
{
    //
    public function index(){
	$name="Masud Alam";
    	$date=date('Y-m-d');
    	return view('home',compact('name', 'date'));

    }
}

Fetch data From your Database in Laravel Controllers

Laravel provide more controllers features. In laravel you can fire mysql queries in your Controllers also without any route or model.

Connect Database:

To use database in your Laravel Controllers you want to add namespace by using “use” key work, as like:

use DB;

see the full example and sample output:

<?php

namespace test\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use test\Http\Requests;

class homeController extends Controller
{
    //

    public function index(){
    	$students = DB::table('students')->get();
    	return view('test',['students'=>$students]);
    }
}

Now create test.php file in resources\views\ folder like this example

 <?php
 foreach($students as $student){
 	echo $student->name,"<br>";
 }
 ?>

Now, you can execute “http://localhost:8000” url in your browser, and you’ll get output as like:

Controllers with database connection

Controller with database connection

Passing parameter to controller from route in laravel

First modify your route as like:

Route::get('/{param}', [email protected]');

Now go to your index function in homeController and modify index function as like:

<?php

namespace test\Http\Controllers;
use Illuminate\Http\Request;
use test\Http\Requests;

class homeController extends Controller
{
    public function index($param){
    	return $param;
    }
}

Now, you can execute “http://localhost:8000/Hello Bangladesh” url in your browser, and you’ll get output as like:

Passing Data From Router to Controller

Passing Data From Router to Controller

Hi, My name is Masud Alam, love to work with Open Source Technologies, living in Dhaka, Bangladesh. I graduated in 2009 with a bachelor’s degree in Engineering from State University Of Bangladesh, I’m also a Certified Engineer on ZEND PHP 5.3, I served my first five years a number of leadership positions at Winux Soft Ltd, SSL Wireless Ltd, CIDA and MAX Group where I worked on ERP software and web development., but now i’m a co-founder and Chief Executive Officer and Managing Director of TechBeeo Software Consultancy Services Ltd. I’m also a Course Instructor of ZCPE PHP 7 Certification and professional web development course at w3programmers Training Institute – a leading Training Institute in the country.

Leave a Reply

Your email address will not be published. Required fields are marked *