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 !

Become a more social person