Reputation: 2029
I want to schedule a task that will send an email notification to selected users that have placed reservation for a particular product when a certain condition is met. Here's how the task is setup
$schedule->call(function () {
// get reservation collection
$reservations = Reservation::all();
// iterate over reservation collection
foreach ($reservations as $reservation) {
// get difference in hours between now and product start date
$timeDiff = Carbon::parse($reservation->product->start)->diffInHours();
// send mail notification to reservation owners
if ($timeDiff > 2) {
// get users who reserved the product
$users = Reservation::where('product_id', $reservation->product_id)->pluck($reservation->user->username);
//notify user
Notification::send($users, new ReservedProductPurchase($reservation));
}
}
})->everyMinute();
When I run the command php artisan schedule:run
, it throws an error
SQLSTATE[42S22]: Column not found: 1054 Unknown column '[email protected]' in
'field list' (SQL: selectmymail@domain
.com
fromreservations
whereproduct_id
= 2)
Of course I am not saving emails(username in this case) in my reservations table which is why the error occurs.
The relationship between a user and a reservation is One To Many
which means a user hasMany
reservations and a reservation belongsTo
a user.
How should I go about retrieve a collection of the emails(usernames) that I want the notification sent to?
Upvotes: 1
Views: 66
Reputation: 9161
Notification::send()
wants a collection of notifiable entities not a collection of emails, so first you have to add the correct trait to the User
model:
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
}
Then you can retreive the users that has a certain reservation:
// get users who reserved the product
$users = User::whereHas('reservations', function (Builder $query) use ($reservation)
{
$query->where('product_id', $reservation->product_id);
})->get();
Upvotes: 1
Reputation: 14268
Your usage is a bit wrong, the pluck
method accepts the column
name and what you pass is the value, which is the user email. So that's why it says that a column with that email address could not be found. You can try this instead:
Reservation::with('user')
->where('product_id', $reservation->product_id)
->get()
->pluck('user.email')
->toArray()
Upvotes: 2
Reputation: 5712
I don't know what column stores your username field. But assuming the column name is username
. You should pluck that column, not the email
. Like this:
$users = Reservation::where('product_id', $reservation->product_id)->pluck('username');
Basically: pass column name in pluck()
method
Upvotes: 0