我的View
课程中有两位AppServiceProvider
作曲家,位于:
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
View::composer('left', function ($view)
{
if (Auth::check())
{
$user = Auth::user();
// Gets a list of the people the user is following
$usersFollowing = Following::where('user_id', $user->id)
->get();
// More queries here
View::share('usersFollowing', $usersFollowing);
}
});
View::composer('right', function ($view)
{
if (Auth::check())
{
$user = Auth::user();
// Gets a list of the people the user is following
$usersFollowing = Following::where('user_id', $user->id)
->get();
// More queries here
View::share('usersFollowing', $usersFollowing);
}
});
}
}
如您所见,两位作曲家都请求相同的查询数据($usersFollowing
)。这两个布局(left.blade.php
和right.blade.php
)都在我的所有页面上调用(通过将它们包含在基本布局中)。
这个问题是页面在单页加载时请求$usersFollowing
两次。它为left.blade.php
调用一次查询,为right.blade.php
调用一次。
我也在每个作曲家一次调用Auth::user()
两次。
如何防止这些查询被同一个请求调用两次,并且只调用一次?
答案 0 :(得分:0)
我认为将查询移到方法的顶部并在两个View组合器中使用它们很简单。这样您的查询只会运行一次。 以下是我提出的这样做的方法;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
$user = Auth::user();
// Gets a list of the people the user is following
$usersFollowing = Following::where('user_id', $user->id)
->get();
// You can use `use` keyword to access external variables inside callback function.
//Both of these variables will be accessible inside callback
View::composer('left', function ($view) use ($usersFollowing,$user)
{
if (Auth::check())
{
// More queries here
View::share('usersFollowing', $usersFollowing);
}
});
View::composer('right', function ($view) use ($usersFollowing,$user)
{
if (Auth::check())
{
// More queries here
View::share('usersFollowing', $usersFollowing);
}
});
}
}
我希望这会有所帮助,您可以将此方法推广到需要此类功能的任何其他情况。