Laravel 5: Rendering Views to Strings and Returning View Responses With view

April 14, 2018 —John Koster

The view function can be used to return an implementation of "Illuminate\Contracts\View" "\Factory" (by default this is an instance of "Illuminate\View\Factory") or an implementation instance of "Illuminate\Contracts\View\View" (which by default would be an instance of "Illuminate\View\View"). The examples in this section will make use of the default welcome.blade.php example view file that ships with new Laravel installations.

If no arguments are supplied to the view helper function, the Factory implementation will be returned and all available Factory methods will be available to you.

#Signature

The signature of the view function is:

1function view(
2 $view = null,
3 $data = [],
4 $mergeData = []
5);

#Example Use

The following example demonstrates how to check if a particular view exists by name:

1// Check to see if a view exists.
2if (view()->exists('welcome')) {
3 // The welcome view exists.
4}

When arguments are supplied to the view function an internal call to Factory::make will take place and the created View instance will be returned as the result. The $view parameter is the name of the view file, $data is the initial data that will be passed along to the view and $mergeData is simply an additional array of data that can be merged with $data before being supplied to the view. It is important to note that any array or object instance that implements the "Illuminate\Contracts\Support\Arrayable" interface can be supplied as an argument for the $data parameter.

For example, you can pass a "Illuminate\Support\Collection" instance as an argument for $data but not for $mergeData. This will work:

1// Create a new View instance with data.
2$view = view('welcome', collect([
3 'name' => 'John Doe'
4]), ['version' => '1.0.0']);

But this will throw an instance of ErrorException:

1// Create a new View instance with data.
2$view = view('welcome', collect([
3 'name' => 'John Doe',
4]), collect([
5 'version' => '1.0.0'
6]));

#Rendering a View to a String

Sometimes it is useful to store the rendered contents of a view as a string for further processing. The following example demonstrates how to accomplish this using the view helper function:

1$welcomeViewContents = view('welcome')->render();

After the above example has executed, the $welcomeViewContents variable would contain the contents of the welcome.blade.php view file.

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.