3

I am trying to get user's unread notifications though my controller.

This works:

public function notifications(){

    return \App\User::find(auth()->user()->id)->unreadNotifications()->limit(5)->get();
}

This doesn't, it returns an empty collection:

public function notifications(){
    return auth()->user()->unreadNotifications()->limit(5)->get();
}

Could you tell me what I am missing? Thanks in advance.

Using Laravel 5.8 with Backpack 3.5.

The default auth guard of Laravel is overwitten to use Backpack auth in backpack routes, using the UseBackpackAuthGuardInsteadOfDefaultAuthGuard middleware of the permissions manager package. In the rest of the controller auth() and backpack_auth works normally.

Librasulus
  • 138
  • 1
  • 9

2 Answers2

0

Try this:

public function notifications()
    return Auth::user()->unreadNotifications()->limit(5)->get();
}

As said in the docs:

You may access the authenticated user via the Auth facade:

Alternatively, once a user is authenticated, you may access the authenticated user via an Illuminate\Http\Request instance. Remember, type-hinted classes will automatically be injected into your controller methods:

Community
  • 1
  • 1
Piazzi
  • 2,490
  • 3
  • 11
  • 25
0

Auth and auth() likely don't work here because you're using the Backpack For Laravel authentication which uses a different guard than the default one Laravel uses.

This would probably work for you:


backpack_user()->unreadNotifications()->limit(5)->get();

If that works, here's why:

If you take a look at project/vendor/backpack/base/src/helpers.php you'll see that backpack_user() is an alias for backpack_auth()->user() and backpack_auth does a:

return \Auth::guard(backpack_guard_name());

That's the important bit because it grabs the guard defined config/backpack/base.php (which is backpack by default) and uses that instead of Laravel's default guard of web.

Wesley Smith
  • 19,401
  • 22
  • 85
  • 133
  • no change. I have overwritten the default auth guard with the UseBackpackAuthGuardInsteadOfDefaultAuthGuard middleware of backpack permission manager package. In the rest of my controller auth() works normally. My suspicions now are in my route namespace. I am editing my question. Thank you for your contribution. – Librasulus Mar 11 '19 at 11:35