消息计数器显示Laravel中已记录用户的消息总数而不是计数

时间:2017-10-18 04:52:08

标签: php laravel laravel-5

我试图在用户登录时显示未读消息的数量(如果有的话)。问题是当我使用新创建的帐户登录时,我收到了X条未读消息的通知,但没有。

更好地解释它。如果adminuser1发送消息并且user1尚未阅读,则user2登录时会发出有1条未读消息的通知。当user1阅读时,通知将会消失。

我已将此添加到我的ViewComposerServiceProvider启动功能

public function boot()
{

    dd(Auth::user()); <--- return NULL

    $unviewedCustomersMessagesCount = Message::where('read_state', '0')->where('from_admin', '1')->count();
    View::share('unviewedCustomersMessagesCount', $unviewedCustomersMessagesCount);
}

然后我只是在view.blade中显示计数器

{{ $unviewedCustomersMessagesCount }}

如果需要,这是我的Message型号

class Message extends Eloquent 
{
    protected $table = 'messages';
    protected $primaryKey = 'message_id';

    public function user() 
    {
        return $this->belongsTo('App\User', 'user_id', 'user_id');
    }

    public function markAsRead() 
    {
        $this->read_state = '1';
        $this->save();
    }
}

User模型

class User extends Eloquent implements AuthenticatableContract, CanResetPasswordContract
{
    use EntrustUserTrait;
    use Authenticatable, CanResetPassword;

        [....]  

    public function messages()
    {
        return $this->hasMany('App\Message', 'user_id', 'user_id');
    }
}

是否有更好的方法为用户计算消息?

控制器

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function __construct()
    {
            $unviewedCustomersMessagesCount = Message::
            whereRaw('messages.message_id = (select max(message_id) from `messages` m2 where m2.user_id = messages.user_id)')
                ->where('read_state', '0')
                ->where('from_admin', '0')
                ->where('user_id', Auth::user()->user_id)
                ->count();

            View::share('unviewedCustomersMessagesCount',$unviewedCustomersMessagesCount );

    }            
}

3 个答案:

答案 0 :(得分:0)

试试这个..我认为在你的情况下不需要whereraw声明。

view()->composer('layouts.master', function($view){

       $unviewedMessagesCount = 
      Message::where('read_state','=', '0')
           ->where('from_admin','=', '0')              
           ->count();                   
       $view->with('/', $unviewedMessagesCount );
    });

答案 1 :(得分:0)

Messages模型中尝试投射,将$cast添加为:

protected $casts = ["read_state"=>"boolean", "from_admin"=>"integer"];

查看作曲家中尝试获取未读消息,例如:

$messages = \Auth::user()->messages()->where('read_state', false)->where('from_admin', 0)->count();

我不确定from_adminboolean还是integer,您可以根据$casts的要求进行更改,也可以使用true或{{1}查询中包含{}或false

答案 2 :(得分:-1)

您需要将当前用户ID传递给查询,删除原始查询

$currentUserId = Auth::user()->id;
$unviewedMessagesCount = Message::where('read_state', '0')
           ->where('from_admin', '0') 
           ->where('user_id',$currentUserId)             
           ->count();