What are the views?
Views contain the html code required by your application, and it is a method in Laravel that separates the controller logic and domain logic from the presentation logic. Views are located in the resources folder, and its path is resources/views.
Let's see the simple example of views.
Suppose we want to create the view of the contact.
Step 1: First, we create the view file named Contact.php in resources/views directory.
Step 2: Add the following code in web.php.
In the above code, view() method contains two arguments. The first argument is the name of the file that contains the view, and the second argument is the array passed to the given file. In array, we are passing the name variable to the Contact.php file.
Step 3: Enter the URL http://localhost/laravelproject/public/contact to the web browser, then the output would be:
Let's see another example of views.
In this example, we use the view() method in the Controller class.
Step 1: First, I need to create a controller. Suppose I have created the controller named 'PostController', and then add the code given below in a PostController.php file.
Step 2: Now, we create the about.php file in which we add the html code.
Step 3: Last step is to add the route in web.php file.
Step 4: Enter the URL http://localhost/laravelproject/public/post to the web browser.
Nesting the Views
Views can also be nested within the sub-directory resources/views directory.
Let's understand the nested views through an example.
Suppose we want to know the admin details. The view of the admin details is available at the resources/views/admin/details.blade.php directory.
Step 1: First, we create details.blade.php file in the admin folder, and the code of the details.blade.php file is given below:
Step 2: Now, we need to add the display() function in PostController.php file which is returning the view of the 'admin.details'.
Step 3: Lastly, we will add the route in a web.php file.
Step 4: To see the output, enter the url 'http://localhost/laravelproject/public/details' to the web browser.
Determining the existence of view
Laravel also allows you to determine whether the view exists or not by using the View fašade. We can use the exists() method that returns true if the view exists.
Suppose we want to check whether the view of the admin.details exists or not, then we can use the following code in PostController.php file:
In the above code, View::exists('admin.details') method determines whether the admin.details exist or not. If it exists, then the 'if' statement is executed; otherwise, the 'else' statement is executed.
Enter the url 'http://localhost/laravelproject/public/details' to the web browser, and then the output would be: