【问题标题】:Returning same variable to every controller in laravel将相同的变量返回给laravel中的每个控制器
【发布时间】:2018-09-27 09:34:14
【问题描述】:

我需要向几乎每个view 页面发送相同的结果,因此我需要绑定variables 并与每个控制器一起返回。

我的示例代码

public function index()
{
    $drcategory = DoctorCategory::orderBy('speciality', 'asc')->get();
    $locations = Location::get();

    return view('visitor.index', compact('drcategory','locations'));
}

public function contact()
{
    $drcategory = DoctorCategory::orderBy('speciality', 'asc')->get();
    $locations = Location::get();

    return view('visitor.contact', compact('drcategory','locations'));
}

但正如您所见,我需要一遍又一遍地编写相同的代码。如何编写一次并在需要时将其包含在任何函数中?

我考虑过使用构造函数,但我不知道如何实现它。

【问题讨论】:

  • 你有没有想过创建一个trait,你可以在需要的时候添加上面的功能?
  • 一种简单的方法是:为名为@9​​87654325@和$this->data["locations"]的变量添加值,在你的构造中,在返回视图之前,你可以这样写$data = $this->data;return view('visitor.contact', compact('data'));。您可以将更多变量添加到data 数组中。
  • 你想与evey视图共享这个变量(其他控制器的句柄)还是突出这个控制器的视图句柄?
  • 我想将此变量共享给仅此控制器的视图。

标签: laravel eloquent laravel-controller


【解决方案1】:

您可以通过使用AppServicerProvider 中的View::share() 函数来实现此目的:

App\Providers\AppServiceProvider.php:

public function __construct()
{
   use View::Share('variableName', $variableValue );
}

然后,在您的控制器中,您照常调用 view

public function myTestAction()
{
    return view('view.name.here');
}

现在你可以在视图中调用你的变量了:

<p>{{ variableName }}</p>

您可以在docs阅读更多内容。

【讨论】:

  • 请解释View::share() 的作用以及它将如何解决问题。
  • 我的意思是你应该向回答问题的人解释这一点。我没问。
【解决方案2】:

有几种方法可以实现这一点。

您可以使用serviceprovider,或者如您所说,在constructor 中使用。

我猜你会在你的代码的更多部分之间共享这个,而不仅仅是这个controller,为此,如果代码那么短且专注,我会使用静态调用进行service

如果您完全确定这只是controller 的一个特例,那么您可以这样做:

class YourController 
{

    protected $drcategory;

    public function __construct() 
    {

       $this->drcategory = DoctorCategory::orderBy('speciality', 'asc')->get();

    }

   // Your other functions here

}

最后,我仍然会将您的查询放在 Service 或 Provider 下,并将其传递给控制器​​,而不是直接在那里。也许有一些额外的探索? :)

【讨论】:

    【解决方案3】:

    为此,您可以使用 laravel 的 View Composer Binding 功能

    AppServiceProvider

    的启动函数中添加这个
        View::composer('*', function ($view) {
                    $view->with('drcategory', DoctorCategory::orderBy('speciality', 'asc')->get());
                    $view->with('locations', Location::get());
                }); //please import class...
    

    当您访问每个页面时,您每次都可以访问 drcategorylocation 对象 并且无需向每个控制器发送 drcategorylocation 即可查看。

    编辑你的控制器方法

    public function index()
    {
        return view('visitor.index');
    }
    

    【讨论】:

      【解决方案4】:

      @Sunil 提到 View Composer Binding 是实现这一目标的最佳方式。

      【讨论】:

        猜你喜欢
        • 2015-07-24
        • 2019-09-10
        • 1970-01-01
        • 2018-10-31
        • 1970-01-01
        • 2022-07-28
        • 1970-01-01
        • 2018-01-06
        相关资源
        最近更新 更多