Reputation: 522
I'm trying to get the numbers of records from my notifications, where the candidate_user_id column from inside the data attribute is the same as the UserId (Authenticated User).
After I dd, I was able to get the data from all of the records in the table by using the pluck method (Line 1). I then tried to use the Where clause to get the items that I need but this just didn't work, it was still returning all of the records in the table.
DashboardController.php:
public function index()
{
$notifications = Notification::all()->pluck('data');
$notifications->where('candidate_user_id', Auth::user()->id);
dd($notifications);
}
Here is a partial screenshot of the data that is being plucked.
How can I get the data from this, in a way like this ->where('candidate_user_id', Auth::user()->id);
?
Upvotes: 0
Views: 3995
Reputation: 50491
If data
was a JSON field on the table you could try to use a where
condition to search the JSON using the ->
operator:
Notification::where('data->candidate_user_id', Auth::id())->pluck('data');
Assuming you only want this data
field and not the rest of the fields, you can call pluck
on the builder directly. There isn't much reason to hydrate Model instances with all the fields to then just pluck a single field from them if it is just a table field, so you can ask the database for just the field you want.
Upvotes: 2
Reputation: 4684
If you want to access all notifications for the auth
user.
$user = auth()->user();
dd($user->notifications->pluck('data'));
If you really want to do in your question way, here is how.
$notifications = Notification::all()->pluck('data');
$notifications = $notifications->where('candidate_user_id', Auth::user()->id)
->all();
This assumes you that you did not modify the default laravel notifications relationship and database migration setup. If you have modified some of the default ones, you need to provide how you modify it.
Upvotes: 0
Reputation: 28795
The data in the data
field is a json string, so you can tell Laravel to automatically cast it as an array using the $casts
property on each of the models that is notifiable.
For instance, if you have a User
model which uses the trait (ie has use Notifiable
), add this:
protected $casts = [
'data' => 'array',
];
Upvotes: 0