Reputation: 7128
I want to send email to users who have activate option in second table but not sure how to.
mailings
tablelatest_blog
column is set to on
$latest_blog = Mailing::where('latest_blog', 'on')->pluck('user_id');
$users = User::whereIn('id', [$latest_blog])->get();
foreach($users as $user){
Mail::to($user->email)->send(new BlogUpdates($user, $post));
}
dd($latest_blog);
returns
Collection {#1705 ▼
#items: array:5 [▼
0 => 41
1 => 51
2 => 42
3 => 60
4 => 61
]
}
dd($users);
returns only 1 user while all users have column latest_blog
set to on
. so basically it supposed to return 5 users and not 1.
Collection {#1758 ▼
#items: array:1 [▼
0 => User {#1756 ▶}
]
}
Any idea?
Mailing model
protected $fillable = [
'user_id', 'interests', 'security', 'latest_projects', 'latest_blog'
];
public function user()
{
return $this->belongsTo(User::class);
}
User model
protected $fillable = [
'name', 'username', 'email', 'password', 'points', 'google2fa_secret'
];
public function mails()
{
return $this->hasOne(Mailing::class);
}
Mailing Schema
Schema::create('mailings', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->nullable()->unique();
$table->string('interests')->default('on');
$table->string('security')->default('on');
$table->string('latest_projects')->default('on');
$table->string('latest_blog')->default('on');
$table->timestamps();
});
Schema::table('mailings', function (Blueprint $table) {
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
Upvotes: 1
Views: 2701
Reputation: 9369
Everything you are doing is correct but you are adding extra array in whereIn
clause. Since, pluck already returns a array, there is no need to add [ ] again in whereIn
clause so,
your code should be
$latest_blog = Mailing::where('latest_blog', 'on')->pluck('user_id');
$users = User::whereIn('id', $latest_blog)->get();
foreach($users as $user){
Mail::to($user->email)->send(new BlogUpdates($user, $post));
}
I hope you understand.
Upvotes: 2
Reputation: 167
This will work:
$latest_blog = Mailing::where('latest_blog', 'on')->get()->pluck('user_id');
// dd($latest_blog);
$users = User::whereIn('id', $latest_blog->toArray())->get();
foreach($users as $user){
Mail::to($user->email)->send(new BlogUpdates($user, $post));
}
Upvotes: 1