Passing Company Data to All controller in Laravel 6.x

431 Views Asked by At

I am building an app where each company have multiple users. And all users can upload documents/images/xls etc. I want to keep all company data in company separate folder. To complete this I am checking the company detail for every user and then upload data to company specific folder. Can I check company database once per user login and share user's company details to all controller and can easily access.

3

There are 3 best solutions below

0
On

You can make the helper function to use in controllers or blades files.

Let’s create a helper!

  1. Create a simple PHP file.

Create Helper.php inside the app directory or wherever directory you want.

<?php
/**
* get company data
*
*/
function companyData()
{
   // Create logic of company data
   // return company data
}
  1. Autoload Composer

After we created our helper, Laravel won’t recognize our file so we need to register the helper file to our composer.json. Add File array inside the autoload section. It may look like this:

"autoload": {
   "classmap": ["database"],
   "psr-4": {"App\\": "app/"},
   "files" : ["app/Helper.php"]
}

Then don’t forget to run

composer dumpautoload
  1. Using helper function

Our helper is autoloaded now, so we should be able to use our helper immediately on different controllers. Just call our function in any class

$companyData = companyData();

or in blade view

{{ companyData() }}

Let me know if you are facing an issue.

5
On

Use view composer in your AppServiceProvider

App\Providers\AppServiceProvider.php

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        view()->composer('*',function($view) {
            if(auth()->user()) {
              $comanyData = App\Company::where('user_id',auth()->user()->id);
              $view->with('companyData', $companyData);
            }
        });
    }
}
0
On

Below is how to share a variable with your entire application via the AppServiceProvider, You can also do this inside of your base controller in the construct method.

File: App\Providers\AppServiceProvider.php

<?php

namespace App\Providers;

use View;
use Illuminate\Support\ServiceProvider;

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');
    }
}


You can then access $key inside of any view.