php - Laravel Controller 功能全局应用

标签 php laravel

我的网站收件箱页面有一个 Controller ,该 Controller 中有一个函数可以计算用户未读消息的数量。

    public function updateUnreadCount() {
        if (Auth::check()) {
            $value = 0;
            $messages = Message::where(function($query) {
                return $query->where('recipient_id', Auth::user()->id)->where('reci_read', 0)
                ->orWhere('user_id', Auth::user()->id)->where('sender_read', 0);
            }); 

            foreach ($messages as &$value) {
                    ++$value;
            };

            Auth::user()->update([
                'unread_msg' => $value,
            ]);
        };  
    }   

我想知道的是,如何让这个函数对所有经过身份验证的用户全局触发,以便我可以在每个页面上显示未读消息的数量?

最佳答案

使用View Composer

View composers are callbacks or class methods that are called when a view is rendered.

假设您的未读收件箱位于navbar.blade.php

        // From the documentation, using Closure based composers...
        View::composer('navbar', function ($view) {
            if(Auth::user()) {
              //logic here
            }
        });

关于php - Laravel Controller 功能全局应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39564905/

相关文章:

php - 将插入与搜索分开 MYSQL PHP

php - 将外部产品图片添加到 opencart

php - 如何从 laravel 分页的第一页中删除查询字符串页面?

javascript - 如何更新多个 HTML 页面中的静态内容

javascript - 无法通过ajax传递表单的输入值

php - Laravel 5.2 时间戳

mysql - SQLSTATE[23000] : Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails error in Laravel 4

php - laravel Controller 不可实例化

php - Laravel 从关系中获取第一项的模型

用户 friend 的 Php 爆炸或唯一 Mysql 表?