In laravel its easy to share varible from controller to view using view function but sometimes we need to share some specific information to all pages of our website for examle sharing the site settings, user info etc. so in this case we require to share a varible across the all views of our application.
In laravel there is many methods to share the varibles across the views like using middleware, providers or base controller etc.
In this article i will show you to share variables between all views in laravel 8.
So to use it in your application you call directly in AppServiceProvider boot function as below
View::share('key', 'value');
Let’s take an example step by step
Step 1 : Create a controller
Create the controller and add the necessary imports and class. You can create by Laravel artisan or manually.
php artisan make:controller ArticleController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Article;
class ArticleController extends Controller
{
public function share1(Request $request)
{
return view("articles.share1");
}
public function share2(Request $request)
{
return view("articles.share2");
}
}
}
Here, we create 2 methods to share the same varibles in both methods.
Step 2: Create blade file for view
Create two file as we called in our controller one share1.blade.php and other is share2.blade.php
<h1>Readerstacks shared {{$sharekey}} here</h1>
and second
<h1>Readerstacks shared 2 {{$sharekey}} here</h1>
In above code we have $sharekey
and if you noticed we have not assigned this key in out controller.
Step 3: Create routes
Now, open the routes/web.php
and add below routes
<?php
use App\Http\Controllers\ArticleController;
use Illuminate\Support\Facades\Route;
Route::get('/share-variable1',[ArticleController::class, 'share1']);
Route::get('/share-variable2',[ArticleController::class, 'share2']);
Step 3: Create shared variable in AppServiceProvider
Now, open app\Porviders\AppServiceProvider.php and write in boot method
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\View;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
View::share('sharekey', 'This is shared');
}
}
As you can see i have imported use Illuminate\Support\Facades\View;
and used in boot method as below
View::share('sharekey', 'This is shared');
now run the test and check our implementation by running artisan serve command in terminal
php artisan serve
Screenshot