【发布时间】:2018-03-11 17:13:03
【问题描述】:
我需要在大多数视图中访问一些数据(用户详细信息)。我做了什么:
我创建了 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 );
}
}
一切正常,但是当我查看调试栏时,它会显示每个视图执行的相同查询,例如,如果我定义 ['includes.header','profile'] 如果 ['includes.header ','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 个查询!我错过了什么?
【问题讨论】:
标签: php mysql laravel laravel-5 blade