1

I'm not sure if my title is correctly done, but what I'm trying to do is get all the notifications that a user didn't read. I have 2 tables the first table is notifications and the second one is read_notifications.

Here is my code in User.php model

$read = DB::table('read_notifications')->select('notification_id')->where('user_id', $this->id)->get();
$unread = Notification::whereNotIn('id', $read)->get();

Here I'm getting all the notification IDs in the read_notifications table and I want to put them in the $unread statement.

The error I get when I do this is

Object of class stdClass could not be converted to string

Chibi
  • 21
  • 3
  • Does this answer your question? [laravel collection to array](https://stackoverflow.com/questions/35284974/laravel-collection-to-array) – Collin Apr 29 '20 at 12:12
  • I did try that, but I still got the same error – Chibi Apr 29 '20 at 12:28
  • Do you have set relations between `Notification` and `ReadNotification`? Is there `ReadNotification` model at all? I presume it can be done with `whereDoesntHave` method with properly set relations. – Tpojka Apr 29 '20 at 14:14

3 Answers3

0
Notification::whereNotIn('id', $read)->get();

$read is an object and id should be a string (or integer). You should use an id field from your $read object like $read[$i]->id.

Also whereNotIn needs an array as a second argument, so you need to collect your IDs from $read to an array like [1,2,3].

  • That is what I'm trying to do, I'm trying to get my ids to looks like `[1,2,3]`, so that I can use it in the `whereNotIn` statement – Chibi Apr 29 '20 at 12:30
0

for whereNotIn to work $read should be an array.

 $read = DB::table('read_notifications')->select('notification_id')->where('user_id', $this->id)->get();
foreach($read as $re)
   $ot[] = $re->notification_id;
$unread = Notification::whereNotIn('id', $ot)->get();

OR you can use pluck

 $read = DB::table('read_notifications')->where('user_id', $this->id)->pluck('notification_id');

 $unread = Notification::whereNotIn('id', $read)->get();
Jithesh Jose
  • 1,781
  • 1
  • 6
  • 17
0

Thanks for helping. I found what I needed, I needed to use the pluck method.

Here is the updated code

$read = DB::table('read_notifications')->select('notification_id')->where('user_id', $this->id)->pluck('notification_id');
$unread = Notification::whereNotIn('id', $read)->get();
Chibi
  • 21
  • 3