Preloader
Laravel
  • Estimated reading time: 1 Minute

How to render a view and save its html content in a variable in laravel

Sometimes, instead of return a specific view as a response (html response), you may need to retrieve instead the content generated by a view to use it as you want i.e a custom JSON response, XML responses etc.

You may not achieve it by yourself (and even more if you're a newbie laravel developer) as this feature is not so intuitive, however not easy to understand or do.

To get the HTML content of a laravel view, independently of whether you're in a controller or not :

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use View;

class DefaultController extends Controller
{
    public function index()
    {
        $view = View::make('welcome', [
            'data' => 'Hello World !'
        ]);

        $html = $view->render();
        // or cast the content into a string
        // $html = (string) $view;
    }
}

Note: if you get an error like Class 'App\Http\Controllers\View' not found, then cast the View class without the global namespace with the following snippet instead (Use \View instead of View).

$view = \View::make('welcome', [
       'data' => 'Hello World !'
]);

The View class will be available "anywhere" in your project. It is an alias given as default in project/config/app.php for Illuminate\Support\Facades\View::class.

Have fun !

Share:
Carlos Delgado

Carlos Delgado

Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Related articles
How to highlight code on the server side with PHP in Laravel
27 Sep, 2017
  • Estimated reading time: 4 Minutes
How to merge multiple PDFs in Laravel
27 Sep, 2017
  • Estimated reading time: 5 Minutes
How to implement a PHP Debugging Bar in Laravel 5.4
26 Sep, 2017
  • Estimated reading time: 3 Minutes
How to create a PSR-6 file system cache for Guzzle in Laravel 5.4
26 Sep, 2017
  • Estimated reading time: 5 Minutes
Our Sponsors

Our blog is proudly supported by industry-leading sponsors.