November 20, 2016 —John Koster
view($view = null, $data = [], $mergeData = [])
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:
1<?php2 3// Check to see if a view exists.4if (view()->exists('welcome')) {5 // The welcome view exists.6}
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<?php2 3// Create a new View instance with data.4$view = view('welcome', collect([5 'name' => 'John Doe'6]), ['version' => '1.0.0']);
But this will throw an instance of ErrorException
:
1<?php2 3// Create a new View instance with data.4$view = view('welcome', collect([5 'name' => 'John Doe',6]), collect([7 'version' => '1.0.0'8]));
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<?php2 3$welcomeViewContents = view('welcome')->render();
After the above example has executed, the $welcomeViewContents
variable would contain the contents of the welcome.blade.php
view file.
∎
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.