Views in Laravel

0
1455

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:
  • Since we can display the output generated by controller to the outside world using views, there are many ways to pass values to a view.
  1. 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
  2. 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.
  3. 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:
  • 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:
    • Now each time the users view is rendered the cnt data will be bound to the view.
    • There is no special convention as to where to store the view composer file. We can store it anywhere as long as it can be autoloaded using the directives in composer.json file.
  • View Creators:
    • 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:

Thus we learned some important points about views in this Views is Laravel in this tutorial.

LEAVE A REPLY

Please enter your comment!
Please enter your name here