Есть три разных способа решения вашей задачи
* Промежуточное программное обеспечение
* BaseClass
* JavaScript
промежуточное ПО и базовый контроллер аналогичны
Промежуточное программное обеспечение
public function handle($request, Closure $next)
{
$notificationCount = 1;// query the database here and get notification for your
// add $notificationCount to your request instance
$request->request->add(['notificationCount' => $notificationCount]);
// call the middleware next method and you are done.
return $next($request);
}
и теперь вы можете прикрепить это промежуточное ПО к вашим маршрутам или группе маршрутов
BaseController
class MyController extends Controller
{
function __construct()
{
$this->middleware(function ($request, $next) {
$notificationCount = 1;// query the database here and get notification for your
// add $notificationCount to your request instance
$request->request->add(['notificationCount' => $notificationCount]);
// call the middleware next method and you are done.
return $next($request);
});
}
}
и теперь вы можете расширить свой контроллер с MyController
вместо Controller
, а затем вы можете использовать что-то подобное
{{ request('notificationCount') }}
Javascript
Создайте функцию / контроллер и верните количество уведомлений как возвращаемое
class NotificationCounterController extends Controller
{
function getNotificatioCount()
{
$notificationCount = 1;
return ['count' => $notificationCount];
}
}
и нельзя делать вызов ajax при событии загрузки документа.
это хорошо, если вы хотите обновлять уведомления каждые несколько раз. как вы можете совершать ajax-вызовы каждые 5 секунд.