Today we are going to learn about views in this Views in Laravel tutorial.
- View in laravel has the same task as in any CMV architecture model. View is used to present the output on the browser in HTML format.
- View typically contain HTML of the application and separates the controller or domain logic from its presentation logic, thus providing a simplified way of working with the application.
- Views are stored in app/viewsdirectory.
- An example of a view is shown below:
<html> <body> <h1>WELCOME <?php echo $nm; ?></h1> </body> </html>
- The view may be returned or displayed on the browser using the following:
- Here we have passed the view to the route to display it on the browser. To return a view to browser, view::make() method is used.
- The first parameter passed to the make() method is the view file greet.php which is stored in the app/views folder/directory. The second parameter is the array of values passed to the view file.
- The values passed in the array are passed as the key-value pair.
- These values are used in the view file using the key of the value as a variable. i.e. the value ‘Victor’ will be included in the view file greet.php as
- We can also pass the array directly as shown below:
- Here $data is the string array containing the key-value pairs of the values passed.
- These values can be used in the view using the keys as variables.
- We can even share the data with all views.
- We can do this using the view helper, using service provider’s boot method or a wildcard view composer.
- Example of view helper: view()->share(‘data’,[1,2,4]);
- Example of view facade: view::share(‘data’,[1,2,3]);
- Example of service provider’s boot method:
Route::get(‘/’,function() { return view::make(‘greet’, array(‘nm’=>’Victor’)); });
$value = View::make('greet', $data);
<?php namespace App\Providers; class AppServiceProvider extends ServiceProvider { public function boot() { view()->share('key', 'value'); } }
- View Composers
- View composers are the class methods that can be called when the view is rendered.
- If we want to pass the data to a view each time it is rendered throughout the application, a view composer can organize the code in a single location.
- Thus view composers function like view models or presenters.
- A view composer can be defined as follows:
View::composer('users', function($view) { $view->with('cnt', User::count()); });
- View creator is same as the view composer, however they are fired immediately when the view is instantiated.
- To register a view creator, simply creator method is used as shown below:
View::creator('users', function($view) { $view->with('cnt', User::count()); });
Thus we learned some important points about views in this Views is Laravel in this tutorial.