Rom*_*LTU 5 php mysql laravel blade laravel-5
我需要在大多数视图中访问一些数据(用户详细信息)。我做了什么:
我创建了 ComposerServiceProvider
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class ComposerServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
view()->composer(
['includes.header','profile'],
'App\Http\ViewComposers\CustomerComposer'
);
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
//
}
}
Run Code Online (Sandbox Code Playgroud)
创建 CustomerComposer 类
<?php
namespace App\Http\ViewComposers;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;
use Modules\Customers\Entities\CustomerDetail;
class CustomerComposer
{
public $customer = [];
/**
* Bind data to the view.
*
* @param View $view
* @return void
*/
public function compose(View $view)
{
$user = Auth::guard('customer');
$this->customer = CustomerDetail::where('user_id',$user->id())->first();
$view->with( 'customer', $this->customer );
}
}
Run Code Online (Sandbox Code Playgroud)
一切正常,但是当我查看调试栏时,它会显示每个视图执行的相同查询,例如,如果我定义 ['includes.header','profile'] 如果 ['includes.header',' 相同的 SQL 将执行两次profile','something_else'] 3 次,依此类推...
在这种情况下,查询是
select * from `customer_details` where `user_id` = '1' limit 1
select * from `customer_details` where `user_id` = '1' limit 1
Run Code Online (Sandbox Code Playgroud)
如果我提供通配符
view()->composer(
['*'],
'App\Http\ViewComposers\CustomerComposer'
);
Run Code Online (Sandbox Code Playgroud)
它将生成 23 个查询!我在这里错过了什么?
好的,我想我找到了解决方案。在 ComposerServiceProvider 类中:
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->app->singleton(\App\Http\ViewComposers\CustomerComposer::class);
}
Run Code Online (Sandbox Code Playgroud)
那个。
在 Laravel 文档中
注册单身人士
有时,您可能希望将一些只应解析一次的内容绑定到容器中,并且在后续调用容器时应返回相同的实例: