Home > OS >  Add data (array) Globally in Laravel 8
Add data (array) Globally in Laravel 8

Time:01-25

How to add data in array global in appServiceProvider of Laravel which could be used globally for select option field in blade.php

CodePudding user response:

You can use View::share to share data within all views. Here is an example from the doc

<?php

namespace App\Providers;

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('key', 'value');
    }
}

CodePudding user response:

You can use view()->share in boot function of AppServiceProvider.php Class under Providers to make data accessible globally like

   public function boot()

{


 $departments =[

            'IT'=> 'Information Technology Department',

            'BIL'=> 'Billing Department',

            'ACC'=> 'Accounts Department',
            
        ];

    view()->share('departments',$departments);
    

}

and you can use this data stored in $departmentrespectivly in blade.php

<select>
     <option value="">Choose One</option>
     @foreach($departments as $key=> $value)
     <option value="{{ $key }}">{{ $value }}</option>
     @endforeach
   </select>
  •  Tags:  
  • Related