How to Load and pass data to View in Laravel

Laravel follows Model view controller pattern.

    • Controller – Interact with Model and view.
    • Model – Handles database manipulation.
    • View – Display final UI to the user from where it can interact with the application.

Laravel comes with Blade templating engine which makes easier to create pages. Blade view file compiled into plain PHP code.

Blade view files has .blade.php extension.

You can use PHP code in it.

I am assuming you have already created a Laravel project if not then you can view my earlier tutorial.

In this tutorial, I will create a simple application where pass data to view.

How to Load and pass data to View in Laravel


Contents

  1. Create Controller
  2. Route
  3. Views
  4. Output
  5. Conclusion

 


1. Create Controller

Controller files are managed in app/Http/Controllers/ directory.

  • Open Command Prompt.
  • Navigate to project directory.
  • Now, execute php artisan make:controller PagesController. Here, I created PagesController.

How to Load and pass data to View in Laravel

  • A new controller is created in app/Http/Controllers directory.

How to Load and pass data to View in Laravel


Syntax – Load a View

view([ view-name ]);

Syntax – Pass data to View

1.compact() –

Pass single value

view([ view-name ], compact( variable-name ));

Multiple values

view([ view-name ], compact( [variable-name1,variable-name2,...] ));

2. with() – 

Pass single value

view([ view-name ])->with(key-name, value);

Multiple values

view([ view-name ])->with( [key-name1 => value1, key-name2 => value2, ...]);

In the controller, I created 3 methods to load a view and pass data.

1. index() – Load index view and pass $titleName.

2. about() – Load about view and pass $title.

3. contact() – Load contact view and pass $data array where initialize title key.

NOTE – If view file is stored in another directory inside views/ directory then it will locate using (.) symbol e.g. pages.index. Here, pages is a directory name and index is view file name.

Completed Code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PagesController extends Controller{
 
  public function index(){
    $titleName = "HomePage";
    return view('pages.index',compact('titleName'));
  }

  public function about(){
    $title = "About Us";
    return view('pages.about')->with('title', $title);
  }

  public function contact(){
    $data = array();
    $data['title'] = "Contact";
    return view('pages.contact')->with($data);
  }
}

2. Route

Need to define the route to access the pages.

Open web.php in routes/ directory.

Here, I defined 3 routes for the homepage, about, and contact.

Completed Code

<?php

// Controller-name@method-name
Route::get('/', 'PagesController@index'); // localhost:8000/
Route::get('/about', 'PagesController@about'); // localhost:8000/about
Route::get('/contact', 'PagesController@contact'); // localhost:8000/contact

3. Views

Views files are managed in resources/views/ directory.

I created separated directories – includes, and pages to manage views files.

Here, created 4 files –

  • includes/app.blade.php
  • pages/index.blade.php
  • pages/about.blade.php
  • pages/contact.blade.php

How to Load and pass data to View in Laravel


includes/app.blade.php

This is a template file which will extend on index, about, and contact views.

Here, create a common layout for pages but the make content section dynamic.

For this use @yield('content') where pass the string value. This is specified using @section in other views pages.

NOTE – This layout is extend on other pages using @extends('includes.app'). The content is specify between @section('content') and @stop which will replace @yield('content').

Completed Code

<!doctype html>
<html>
  <head>
    <title>Laravel Application</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  </head>
  <body>
    <nav class="navbar navbar-inverse">
     <div class="container-fluid">
       <div class="navbar-header">
         <a class="navbar-brand" href="/">Makitweb</a>
       </div>
       <ul class="nav navbar-nav">
         <li><a href="/">Home</a></li>
         <li><a href="/about">About Us</a></li>
         <li><a href="/contact">Contact Us</a></li>
       </ul>
     </div>
    </nav>
    <div class='container'>
      <div class='row'>
        @yield('content')
      </div>
    </div>
  </body>
</html>

pages/index.blade.php

Extends the app view which is stored in includes/ directory using @extends('includes.app').

Specify HTML content between @section('content') and @stop. This replaces the @yield('content') in the template file.

In <h1> tag pass $titleName between {{ }} which is passed from the controller.

NOTE – The @section([value]) contains [value] is defined value in @yield([value]).

Completed Code

<!-- Extends template page from includes directory-->
@extends('includes.app')

<!-- Specify content -->
@section('content')
<h1>{{$titleName}}</h1>
<p>Page Content</p>
@stop

pages/about.blade.php

@extends('includes.app') App template.

Specify HTML content between @section('content') and @stop.

In <h1> tag pass $title between {{ }} which is passed from the controller.

Completed Code

<!-- Extends template page from includes directory-->
@extends('includes.app')

<!-- Specify content -->
@section('content')
<h1>{{$title}}</h1>
<p>Page Content</p>
@stop

pages/contact.blade.php

@extends('includes.app') App template.

Specify HTML content between @section('content') and @stop.

In <h1> tag pass $title between {{ }} which is passed from the controller.

Also, create a <form > with some input element.

Completed Code

<!-- Extends template page from includes directory-->
@extends('includes.app')
<style>
table td{
  padding-bottom: 10px;
}
</style>

<!-- Specify content -->
@section('content')
<h1>{{$title}}</h1>
<form>
 <table width='100%'>
   <tr>
    <td>Name</td>
    <td><input type='text' class='form-control' name='name'></td>
   </tr>
   <tr>
    <td>Subject</td>
    <td><input type='text' class='form-control' name='subject'></td>
   </tr>
   <tr>
    <td>Content</td>
    <td><textarea class='form-control' name='content'></textarea></td>
   </tr>
   <tr>
    <td></td>
    <td><input type='button' class='btn btn-info' value='Submit' ></td>
   </tr>
 </table>
</form>
@stop

4. Output

How to Load and pass data to View in Laravel


5. Conclusion

Define template layout if you want common layout across all pages with dynamic content. Extend it on the page where require.

You can either pass data from the controller using compact() or with() while loading the view.

I not used Model in this tutorial, which I show in the upcoming tutorial with database manipulation.

If you found this tutorial helpful then don't forget to share.

3 thoughts on “How to Load and pass data to View in Laravel”

  1. Hi!
    Error in code “php artisan make::” double “::”
    In public function index(){
    $title = “About Us”;” used About. Should be “index”.
    If all the fixes write an error “InvalidArgumentException
    View [pages.index] not found.”.
    What else do I need to fix to work the example?

    Reply

Leave a Comment