Sending multiple emails at once using Laravel 4.2 - laravel-4

I managed to make it work sending email to one user at a time but not to multiple users at one. Although i have tried many ways, below is a sample code using which I am trying to send multiple emails. 

if (isset($_POST['searchbutton'])) {
 $data = $query->where('blood_type', '=', "$search")
 ->Where('state', '=', "$state")->get();

 if (isset($POST['emailbutton'])) {
 foreach ($data as $row)
 Mail::send('emails.notify', array('name' => 'Name'), function($message) {

 $message->to($row->email, $row->name)->subject('Hello');
 });
 }
 }

Thank you.

Here are some suggestion of changes assuming that all the user will receive the same email, means you won't be customizing each email with user's name:
if (isset($_POST['searchbutton'])) {
$data = $query->where('blood_type', '=', "$search")
->Where('state', '=', "$state")->get();
$emails = $query->where('blood_type', '=', "$search")
->Where('state', '=', "$state")->lists('email');
if (isset($POST['emailbutton'])) {
Mail::send('emails.notify', array(), function($message) use ($emails) {
$message->to($emails)->subject('Hello');
});
}
}

The actual error here is that the variable $row is not in the scope of your closure. To correct this, you need to use the use keyword. i.e.
foreach ($data as $row){
Mail::send('emails.notify', array('name' => 'Name'),
function($message) use ($row) {
$message->to($row->email, $row->name)->subject('Hello');
}
);
}
You can read more about PHP closures here.

Related

Laravel query relationship issue

I need to check if inside a relationships there is a given value but i got an error when i try to fetch the variable i need inside the loop. I get "message": "Undefined variable: cat".
Here is my code
$cate = $request->input('category');
foreach ($cate as $key => $cat) {
$restaurants->with(['categories' => function ($query) {
$query->where('name', '==', $cat);
}]);
}
can someone help me figure out?
you must use "whereHas" instead of "with" to check if relationship have pass condition:
$cate = $request->input('category');
foreach ($cate as $key => $cat) {
$restaurants->whereHas(['categories', function ($query) use ($cat) {
$query->where('name', '==', $cat);
}]);
}
and for your questions: import variable to the current scope (the use keyword)
what is inside your $cate variable ?
and what do you want to do ?
If you want to search your Restaurants matching your given categories in your input, then you should do this :
// assuming your $request->input('category') look like this :
$categories = ['foo', 'bar'];
$restaurants = Restaurant::whereHas('categories', function($query) use ($categories){
$query->whereIn('name', $categories);
})->get();
(just for explaining your error, you have to pass you $cat variable to your closure :
$restaurants->with(['categories' => function ($query) use ($cat) {
$query->where('name', '==', $cat);
}]);
you need to just pass the $cat variable to your closure => function ($query) use ($cat)
$cate = $request->input('category');
foreach ($cate as $key => $cat) {
$restaurants->whereHas(['categories' => function ($query) use ($cat) {
$query->where('name', $cat);
}]);
}
use whereHas() to specify additional filters in the relationship.
Show More => https://laravel.com/docs/8.x/eloquent-relationships

how can i perform an update and get in the same query to use in a foreach?

how can i get data from query $ or while updating it?
wanted to run a foreach to send an email when the update was done
$x = encomendas::where('estado', 3)->where('updated_at', '<', $dias2)
->join('distritos', 'encomendas.distrito', '=', 'distritos.id')
->update(['estado' => 4])->get();
foreach ($encomendasnaopagas as $email) {
Mail::send('emails.cliente.cancelada', [
'id_encomenda' => $email->id,
], function ($messagem) use ($email) {
$messagem->from('noreply#cccc.pt', 'xxx');
$messagem->to($email->email)->subject('xxxxx');
});
}
thank you for your help
You can use the same object which you used for update operation.
$encomendasnaopagas = encomendas::where('estado', 3)->where('updated_at', '<', $dias2)
->join('distritos', 'encomendas.distrito', '=', 'distritos.id')
->get();
foreach ($encomendasnaopagas as $value) {
if( $value->update($arrayyouwanttoUpdate)){
// if update is done successfully update() will return true, use that in your if condition
// now use $value to send emails
}
}

Converting multiple same name into one single name using Laravel

I am trying to fetch the user name instead of multi user name but unfortunately, the single user name is not showing.
Controller
public function search(Request $request)
{
$date = explode(' - ', $request->date);
$auth = Auth::user();
$hourLog = Hourlog::with('project', 'user');
if ($request->user) {
$hourLog->whereIn("user_id", $request->user)->get();
} else if ($auth->user_type == 1) {
$hourLog->where("user_id", $auth->id);
}
if ($request->project) {
$hourLog->whereIn("project_id", $request->project)->get();
}
$data = [
"hourlogs" => $hourLog->whereBetween('date', $date)
->orderBy('date', 'desc')
->orderBy('start_time', 'asc')
->get(),
"date"=> $date,
];
return view('cms.projectreport.projectreport-list', $data);
}
html view
#foreach($hourlogs as $hourlog)
<tr>
<td>{{$hourlog->user->name}}</td>
</tr>
#endforeach
Use groupBy() on your query with the user_id:
$data = [
"hourlogs" => $hourLog->whereBetween('date', $date)
->orderBy('date', 'desc')
->orderBy('start_time', 'asc')
->groupBy('user_id')
->get(),
"date"=> $date,
];
This will give you a collection with unique user, containing the related models
You can use distinct to make the query like this:
$data = [
"hourlogs" => $hourLog
->select('user_id')
->whereBetween('date', $date)
->orderBy('date', 'desc')
->orderBy('start_time', 'asc')
->distinct()
->get(),
"date"=> $date,
];

laravel 404 error page , redirect

looking for some help, I'm fetching a survey and questions, from method, when select some survey by id, from a route. But when I delete a survey, and when writing in url like http://localhost/survey_details/27 ( 27 is survey Id , which not exist anymore), I'm getting not some expection or redirection or Page not found info, but getting error where undefined variable $dat. But I need some how to show 404 page not found, or just redirect to other page if id not exist. Can some one help me?
here is my route:
Route::get('survey_draft/{id}', 'SurveyController#editSurveyDraft');
Here is my controller:
public function viewSurvey($id)
{
$object = DB::table('question')
->where('survey_id', '=', $id)
->where('name', '!=', NULL)
->get();
$teamName = DB::table('survey')->where('surveyId', '=', $id)
->join('team', 'survey.teamId', '=', 'team.teamId')
->join('company', 'company.id', '=', 'team.companyID')
->get();
$company = Auth::user()->company;
$data = Survey::where('surveyId', '=', $id)->get();
$teams = Auth::user()->teams;
$checkUserTeam = DB::table('teammembersall')
->where('UserId', '=', Auth::user()->id)
->get();
$members = Survey::where('surveyId', '=', $id)
->join('team', 'team.teamId', '=', 'survey.teamId')
->join('teammembersall', 'teammembersall.TeamId', '=', 'team.TeamId')
->join('users', 'users.id', '=', 'teammembersall.UserId')
->select('users.*')
->whereNotExists(function ($query) use ($id) {
$query->select(DB::raw(1))
->from('answer')
->whereRaw('answer.answerAboutUserId = users.id')
->where('answer.surveyId', '=', $id)
->where('answer.member_id', '=', Auth::user()->id);
})
->get();
$questions = DB::table('answer')->get();
return view('survey_details', ['object' => $object, 'data' => $data, 'teams' => $teams, 'members' => $members, 'questions' => $questions, 'checkUserTeam' => $checkUserTeam, 'teamName' => $teamName, 'company' => $company]);
}
To solve your immediate issue, you could add one of these this after $object ... get() depending on your result. One of them should work.
if(empty($object)){ abort(404); }
or
if(!$object->count()){ abort(404); }
However, your code would be much simpler if you used 2 basic laravel technologies.
ORM instead of DB::...
Route model binding. (which would handle your 404 for you)
https://laravel.com/docs/5.6/eloquent
https://laravel.com/docs/5.6/routing#route-model-binding

laravel send mail to

Good evening everyone, I have some issues, with send mail to:
I have a code in controller, and have data taken from database with joins, this $survey variable shows gives me emails of the survey which belongs to team.
But I need some how to send an email for all emails which I gets from $survey variable. When I put $survey variable inside $message->to($survey); it shows me Undefined variable
my code below , how can I use it. When I put in ->to(); normal one email adress it works, but I need to send same email to all team members
public function startSurvey(Request $req) {
$nameSurvey = $req->input('SurveySelectBox');
$startDate = $req->input('surveyStartDate');
$endDate = $req->input('surveyEndDate');
$data = array(
'updated_at' => Carbon::now(),
'started_at' => $startDate,
'ended_at' => $endDate
);
DB::table('survey')->where('surveyId','=',$nameSurvey)->update($data);
$survey = Survey::where('surveyId' , '=', $nameSurvey)
->join('team','team.teamId', '=', 'survey.teamId')
->join('teammembersall','teammembersall.TeamId', '=', 'team.TeamId')
->join('users','users.id', '=', 'teammembersall.UserId')
->select('users.email')
->get();
Mail::raw('You have new survey to answer: http://localhost:8000/profile', function ($message) {
$message->from('kristijanask#gmail.com', 'New Survey released');
$message->to($survey);
});
return redirect('surveyDrafts');
}
You need to use use ($survey) to use the variable within the Mail anonymous function:
Mail::raw('...text', function ($message) use ($survey) {
$message->from('kristijanask#gmail.com', 'New Survey released');
$message->to($survey);
});
You might also need to use ->pluck() and toArray() on the query result, to make the result an array:
$survey = Survey::where('surveyId' , '=', $nameSurvey)
// long query
->get()
->pluck('email')
->toArray();

Resources