Developer Snippet Diary

What is service container, Service Provider, AppServiceProvider in laravel

service provider:
> A service that is provided to laravel ie Cache Service, Mail Service . They tell Laravel how to boot (initialize) services, bind things into the service container, register events, macros, etc.
Service container (its manage class dependencies)
    A container that make objects of service provider so we can use it in whole application

######################

AppServiceProvider: app/Providers/AppServiceProvider.php
It’s automatically loaded because it’s registered in config/app.php under providers.

It has two methods, register() For binding services, boot() → For initialization after services are registered

  1. FORCE HTTPS

    if ($this->app->environment('production')) {
            URL::forceScheme('https');
    }
     
  2. Custom Blade Directives
    use Illuminate\Support\Facades\Blade;
    public function boot(): void
    {
        Blade::directive('currency', function ($amount) {
            return "<?php echo '$' . number_format($amount, 2); ?>";
        });
    }
    
    @currency(1500)  <!-- outputs $1,500.00 -->
    
  3. Cutom validation rule
    use Illuminate\Support\Facades\Validator;
    public function boot(): void
    {
        Validator::extend('even', function ($attribute, $value, $parameters, $validator) {
            return $value % 2 === 0;
        });
    }
    ####
    $request->validate([
        'number' => 'required|even'
    ]);
    
  4. Share data with views
    // Share the `today_count` variable globally across all views
    // use any viewname in place of * to share only with that ie index
    \Illuminate\Support\Facades\View::composer('*', function ($view) { 
        $todo_list = \App\Models\Todo::where("is_completed","0");
    
        if (\Illuminate\Support\Facades\Auth::check()) {
                $todo_list = $todo_list->where("user_id", $user_id);
        }
        $today_count = $todo_list->count();
        $view->with('today_count', $today_count);
    });
Posted by: R GONDAL
Email: rizikmw@gmail.com