What is Laravel Views ?

Views are stored in resources/views directory. Generally, the view contains the HTML which will be served by the application.

File name : resources/views/test.php

<html>
<body>
<h1>Hello, itechxpert</h1>
</body>
</html>

File name : app/Http/routes.php

Route::get('/test', function() {
return view('test');
});

Test the URL:-

http://localhost:8000/test

Passing Data to Views

Pass an array to view helper function. After passing an array, we can use the key to get the value of that key in the HTML file.

File name : resources/views/test.php

<html>
<body>
<h1><?php echo $name; ?></h1>
</body>
</html>

File name : app/Http/routes.php

Route::get('/test', function() {
return view('test',[‘name’=>’itechxpert’]);
});

The value of the key name will be passed to test.php file and $name will be replaced by that value.


Sharing Data with all Views

There is a method called share() which can be used for this purpose. The share() method will take two arguments, key and value. Typically share() method can be called from boot method of service provider. We can use any service provider, AppServiceProvider or our own service provider.

File name : app/Http/routes.php

Route::get('/test', function() {
return view('test');
});

Route::get('/test2', function() {
return view('test2');
});

Create two view files — test.php and test2.php with the same code. These are the two files which will share data. Copy the following code in both the files. resources/views/test.php & resources/views/test2.php


<html>
<body>
<h1><?php echo $name; ?></h1>
</body>
</html>


Step 3 − Change the code of boot method in the file app/Providers/AppServiceProvider.php as shown below. (Here, we have used share method and the data that we have passed will be shared with all the views.) app/Providers/AppServiceProvider.php


public function boot() {
view()->share('name', 'itechxpert');
}






Previous Next


Trending Tutorials




Review & Rating

0.0 / 5

0 Review

5
(0)

4
(0)

3
(0)

2
(0)

1
(0)

Write Review Here


Ittutorial