How to access variables in all view files in laravel 10

How to access variables in all view files in laravel 10

| |
Image Carousel

Table of Contents                                                                                                    Contents-topics
1 Introduction
2 Changes in AppServiceProvider
3 Access variable in view file


In this tutorial we will discuss about how to access variable in all view files , while working on large web applications and also while working with dynamic web-applications where we have multiple view files with diffrent folder structures and there are some varibles like company details which we have to show dynamically from backend at header and footer or we can take example of menu which we always need on header section then we have options like to call varible directly from view file but that doesn't seems to good practice as a develper so there we access that variables through app\Providers\AppServiceProvider.

2:Changes in AppServiceProvider

In app\Providers\AppServiceProvider under the public function boot()  we create our variable and share with our all view file as shown below
AppServiceProvider code :

namespace App\Providers;
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()
         $name = 'Developer-corner';
        View::share('name', $name);

As shown in code in app\Providers\AppServiceProvider.initally import the view facade and then simply send the variable with view property as shown we are using simple example you may use proper function which is used to get data from backend.

3:Access variable in view file

Now call the view file by route
web.php code

  return view('developerCorner');

Now we can call the $name varibale in any view file
code for view file :Copy

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <h4>Name is {{$name}}</h4>


Tags: laravel , advance laravel , laravel AppServiceProvider , how to access variables in all view files in laravel 10 , how to access variables in all view files in laravel , any way to access single variable in all view files in laravel,laravel , php ,laravel-php , mvc laravel, advance laravel , bugs in laravel , laravel advance level,
0 Comments (Please let us know your query)
Leave Comment
Leave Comment
Articles from other Categories
Load More