1

私はLaravelの初心者で、現在、Laravel 5.2を使用して、基本的に多くの情報を含むダッシュボードであるイントラネットアプリをコーディングしています。要件の1つは、さまざまなストアをナビゲートできることです。アプリの各ページには、ストアのコードが必要です。

現在、すべてのテーブルに列 store_id があり、ルートで GET を使用して、次のようにこの値を取得します。

www.mysite.com/1/employees -> will list all employees from Store 1
www.mysite.com/1/employees/create -> will create employee to Store 1
www.mysite.com/2/financial -> will list all financial widgets with data from Store 2

GET から STORE_ID を削除し、topbar.blade.php 内のすべてのストアで DROPDOWN 選択を使用したいと思います。たとえば、次のようになります。

<select>
  <option selected>Store1</option>
  <option>Store2</option>
</select>

誰かが「Store1」または「Store2」を選択するたびに、StoreController を使用してストア情報を取得し、この変数をすべてのコントローラーとビューで利用できるようにしたいと考えています。次の URL を使用できる場所

www.mysite.com/employees -> will list all employees from "Depending of the SELECT"
www.mysite.com/employees/create -> will create employee to "Depending of the SELECT"
www.mysite.com/financial -> will list all financial widgets with data from "Depending of the SELECT"

View Composer、Facades、ServiceProvide について読んだことがありますが、それらすべてについて本当に混乱しました。

4

3 に答える 3

2

プロバイダーからの共通データを共有することもできます。AppServiceProviderまたは独自のプロバイダー。AppServiceProviderたとえば、ここで使用しています。起動AppServiceProvider方法:

public function boot()
{
    $this->passCommonDataToEverywhere();
}

メソッドに次のように記述します。

protected function passCommonDataToEverywhere()
{
    // Share settings
    $this->app->singleton('settings', function() {
        return Setting::first();
    });
    view()->share('settings', app('settings'));

    // Share languages
    $this->app->singleton('languages', function() {
        return Language::orderBy('weight', 'asc')->get();
    });
    view()->share('languages', app('languages'));
}

この例では、次を使用する必要があります。

use App\Language;
use App\Setting;
于 2016-07-14T06:07:43.240 に答える
1

それほど難しいことではありません。他の方法もあるかもしれませんが、私は次の方法で行うことを好みます。

データの共有:

app/Http/Controllers/Controller.php次のようなコンストラクター関数を開いて追加します。

<?php

namespace App\Http\Controllers;

...

abstract class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function __construct()
    {
        $this->sharedVar = "I am shared.."; // to share across controllers
        view()->share('sharedVar',$this->sharedVar); // to share across views
    }
}

データの使用:

1. コントローラーで:

すべてのコントローラーは、上記のコントローラーを拡張します。したがって、プロパティはすべてのコントローラーで使用できます。

class YourController extends Controller
{
    public function index()
    {
        dd($this->sharedVar);
    }
...
}

2. ビューで:

{{$sharedVar}} // your-view.blade.php

編集:

コントローラとビュー以外の場所にデータを共有したい場合、おそらく最良の方法は次を使用することAppServiceProviderです:

メソッドを開いapp/Providers/AppServiceProvider.phpて更新します。boot()

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $this->app->singleton('sharedVariable', function () {
            return "I am shared";
        });
    }

    ...

}

使用法:

dd(app('sharedVariable')); // anywhere in the application
于 2016-07-14T05:20:33.400 に答える