Laravel Views

What is View?

View is one of the key component in any Model-View-Controller(MVC) framework.Views are meant to hold the presentation logic in any Laravel
application. Views separates presentation logic from the application logic. A view file usually contains the information being presented to a user. View can be a complete web page or parts of page like header and footer.

In Laravel, views are stored in resources/views directory. View for a basic web page can be directly called from route.

Creating a view

Step 1:- Create a new file hello.php and save it at resources/views directory.

Step 2:- Copy and paste following code in the hello.php

Step 3:- Copy and paste following code in the app/Http/routes.php to configure the route for the view created above.

Step 4:- Now open the following URL in the browser to see the output.


Passing Data to a view

If you want to pass some data to a view, it is possible by simply passing a data array consist in key/value pair.


Step 1:- Open the “hello.php” file we created above, and update it with following code.

Step 2:- Open app/Http/routes.php  and re-configure the route as below –

Step 3:- Inside the view, we can retrieve each of the data value by its corresponding key. In “hello.php”, $name will be replaced by it’s value.

Step 4:- Again open the following URL in the browser to see the output.


Sharing Data with all Views

Sometimes we may want to share some common data across all the views. In Laravel, we can do it using share() method. Typically share() method is called from boot method of service provider.


Step 1:- Create two new views as exp1.php and exp2.php, sharing the common variable $name.

Step 2:- Open the exp1.php and exp2.php, and copy the following code in corresponding files.



Step 3:- Open app/Http/routes.php  and define corresponding routes exp1 and exp2.

Step 4:- Open app/Providers/AppServiceProvider.php file and call  share() method inside the boot method as following.

Here we have defined a common variable $name, that can be shared across both the views we created.

Step 5:- Now visit the following URLs in the browser to see the output.