Name : Ankit Raj
Reg : 12217572
Roll : 58
Section : KM033
Date : 07/04/2025
Question 6 :
Data Sharing with View::share() Method Scenario:
You need to share a company’s name and the website URL globally across
all views in your application. This should be done once in the service
provider so that it is available on every page.
Instructions:
1. Use the View::share() method to pass the company name and website
URL globally to all views.
2. Create a Blade view that uses the shared variables to display the
company name and website.
3. Create two blade file and show data
Expected Output:
Every page should display:
• Company Name: Awesome Bookstore
• Website: www.awesomebookstore.com
CODE:
1. In AppServiceProvider.php file in directory app/Http/Providers for
passing values globally to all views:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\View;
class AppServiceProvider extends ServiceProvider
/**
* Register any application services.
*/
public function register(): void
//
/**
* Bootstrap any application services.
*/
public function boot(): void
// This method will pass the follwing details to all views.
View :: share(['companyName' => 'Awesome Bookstore',
'companyWebsite' => 'www.awesomebookstore.com']);
2. In View directory of resource directory, two file will be created one with
home.blade.php and about.blade.php:
1. Home.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<div>
<h1>Company Name: {{ $companyName }}</h1>
<h2>Website: <a
href="http://{{ $companyWebsite }}">{{ $companyWebsite
}}</a></h2>
<div>
</body>
</html>
2. about.blade.php
<!DOCTYPE html>
<html>
<head>
<title>About</title>
</head>
<body>
<h1>Company Name: {{ $companyName }}</h1>
<h2>Website: <a
href="http://{{ $companyWebsite }}">{{ $companyWebsite
}}</a></h2>
</body>
</html>
3. In web.php of directory routes :
<?php
use Illuminate\Support\Facades\Route;
// Following two routes will display two views which have two global data
passed on from appServiceProvider.
// This is root route for which home view will be displayed.
Route::get('/', function () {
return view('home');
});
// This is about route for which about view will be displayed.
Route::get('/about', function () {
return view('about');
});
OUTPUT :
1. Home Page
2. About Page