我需要在大多数 View 中访问一些数据(用户详细信息)。我做了什么:
我创建了 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()
{
//
}
}
创建了 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 );
}
}
一切正常,但是当我查看调试栏时,它显示每个 View 都执行了相同的查询,因此例如,如果我定义 ['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
如果我在中提供通配符
view()->composer(
['*'],
'App\Http\ViewComposers\CustomerComposer'
);
它将生成 23 个查询!我在这里错过了什么?
最佳答案
好的,我想我找到了解决方案。在 ComposerServiceProvider 类中:
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->app->singleton(\App\Http\ViewComposers\CustomerComposer::class);
}
就是它。
在 Laravel 文档中
Registering A Singleton
Sometimes, you may wish to bind something into the container that should only be resolved once, and the same instance should be returned on subsequent calls into the container:
关于php - Laravel View Composer 为每个 View 复制 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46494897/