DeveloperBreeze

Service Providers Development Tutorials, Guides & Insights

Unlock 3+ expert-curated service providers tutorials, real-world code snippets, and modern dev strategies. From fundamentals to advanced topics, boost your service providers skills on DeveloperBreeze.

Laravel Best Practices for Sharing Data Between Views and Controllers

Tutorial November 16, 2024
php

   use Illuminate\Support\Facades\Cache;

   public function boot()
   {
       $navigationMenu = Cache::rememberForever('navigation_menu', function () {
           return [
               ['title' => 'Home', 'url' => '/'],
               ['title' => 'About', 'url' => '/about'],
           ];
       });

       View::share('navigationMenu', $navigationMenu);
   }
   <ul>
       @foreach ($navigationMenu as $item)
           <li><a href="{{ $item['url'] }}">{{ $item['title'] }}</a></li>
       @endforeach
   </ul>

Optimizing Performance in Laravel by Centralizing Data Loading

Tutorial November 16, 2024
php

Alternatively, inject the shared data into the constructor:

   namespace App\Http\Controllers;

   class ExampleController extends Controller
   {
       protected $sharedData;

       public function __construct()
       {
           $this->sharedData = app('sharedData');
       }

       public function index()
       {
           return view('example', [
               'maxUploads' => $this->sharedData['max_uploads'],
               'apiRateLimit' => $this->sharedData['api_rate_limit'],
           ]);
       }
   }

Leveraging Service Providers to Manage Global Data in Laravel

Tutorial November 16, 2024
php

Edit the boot method in app/Providers/CustomDataServiceProvider.php:

   namespace App\Providers;

   use Illuminate\Support\ServiceProvider;

   class CustomDataServiceProvider extends ServiceProvider
   {
       public function boot()
       {
           // Example data
           $globalPreferences = [
               'api_limit' => 100,
               'app_mode' => 'live', // 'maintenance' or 'live'
               'feedback_form_enabled' => true,
           ];

           // Share this data globally
           view()->share('globalPreferences', $globalPreferences);
       }
   }