Yii2 swiftmailer foreach multiple email - yii2

I want to run a code to send email to all users. At first i used this code to run a test.
->setTo([
'john.doe#gmail.com' => 'John Doe',
'jane.doe#gmail.com' => 'Jane Doe',
])
I found out that the mail is 1 mail sent to multiple recipents, while i need to 2 emails to 2 recipients. Because in reality i need to send to over hundred people at once. SO i try foreach loop.
public function contact($email)
{
$users = Users::find()->all();
$content = $this->body;
foreach($users as $user){
if ($this->validate()) {
Yii::$app->mailer->compose("#app/mail/layouts/html", ["content" => $content])
->setTo($user->email)
->setFrom($email)
->setSubject($user->fullname . ' - ' . $user->employee_id . ': ' . $this->subject)
->setTextBody($this->body)
->send();
return true;
}
}
return false;
}
But it only run 1 loop and end.
Please tell me where i'm wrong.
Thank you

the reason just one mail is sent is the
return true
it returns after the first email is sent, you should use try{}catch(){} like below
public function contact($email) {
$users = Users::find()->all();
$content = $this->body;
try {
foreach ($users as $user) {
if ($this->validate()) {
$r = Yii::$app->mailer->compose("#app/mail/layouts/html", ["content" => $content])
->setTo($user->email)
->setFrom($email)
->setSubject($user->fullname . ' - ' . $user->employee_id . ': ' . $this->subject)
->setTextBody($this->body)
->send();
if (!$r) {
throw new \Exception('Error sending the email to '.$user->email);
}
}
}
return true;
} catch (\Exception $ex) {
//display messgae
echo $ex->getMessage();
//or display error in flash message
//Yii::$app->session->setFlash('error',$ex->getMessage());
return false;
}
}
You can either return false in the catch part or return the error message rather than returning false and where ever you are calling the contact function check it the following way.
if(($r=$this->contact($email))!==true){
//this will display the error message
echo $r;
}

Related

Ajax format after submit - Laravel

I'm working on project, I faced some problems
If I fill all fields and then submit there is no problem and it saved to database, but my issue if some field is empty the validation messages error appear in another page as JSON format.
I don't use any AJAX code in my view file.
Here is controller code:
public function store(RegisterRequest $request){
$user = User::create($request->all());
$user->password = Hash::make($request['password']);
if ($request->file('avatar')) {
$image = $request->file('avatar');
$destinationPath = base_path() . '/public/uploads/default';
$path = time() . '_' . Str::random(10) . '.' . $image->getClientOriginalExtension();
$image_resize = Intervention::make($image->getRealPath());
$image_resize->resize(300, 300);
$image_resize->save($destinationPath . '/' . $path);
} else {
$path = $user->avatar;
}
$user->avatar = $path;
$user->save();
return redirect()->route('admin.user.index')->with('message','User created successfully');
And here is RegisterRequest code:
public function rules()
{
return [
'name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:6|confirmed',
'country_code' => 'sometimes|required',
'phone'=>Rule::unique('users','phone')->where(function ($query) {
$query->where('country_code', Request::get('country_code'));
})
];
Can you help me please?
Your errors should be accessible inside blade file with $errors variable which you need to iterate and display the errors.
Link to doc which will help you with the render part - https://laravel.com/docs/7.x/validation#quick-displaying-the-validation-errors
Clearly from doc as well
If validation fails, a redirect response will be generated to send the user back to their previous location. The errors will also be flashed to the session so they are available for display. If the request was an AJAX request, a HTTP response with a 422 status code will be returned to the user including a JSON representation of the validation errors.
https://laravel.com/docs/7.x/validation#creating-form-requests
Also refactor the code a bit as following to run only one query to create a user instead of creating and then updating.
public function store(RegisterRequest $request){
if ($request->hasFile('avatar')) {
//use try catch for image conversion might be a rare case of lib failure
try {
$image = $request->file('avatar');
$destinationPath = base_path() . '/public/uploads/default';
$path = time() . '_' . Str::random(10) . '.' . $image->getClientOriginalExtension();
$image_resize = Intervention::make($image->getRealPath());
$image_resize->resize(300, 300);
$image_resize->save($destinationPath . '/' . $path);
$request->avatar = $path;
} catch(\Exception $e){
//handle skip or report error as per your case
}
}
$request['password'] = Hash::make($request['password']);
$user = User::create($request->all());
return redirect()->route('admin.user.index')->with('message','User created successfully');
}

Deleting data from multiple table

I am trying to delete data from two different table at the same time but it seems like the query is not deleting data. First I will check either user have posted any blog and delete from user and blog if the query is true.
Here is my controller :
public function delete(){
if(isset($_SESSION['userLogId'])){
$selectedId = $this->uri->segment(3);
// getting the current image and unlink it if image exist
$currentImage = $this->User_account_model->currentImage('student', $selectedId);
if($currentImage != null){
$_SESSION['current_image'] = $currentImage->photo;
}
$isDeleted = $this->User_account_model->deleteUser($selectedId);
if($isDeleted == true){
if(isset($_SESSION['current_image']) && !empty($_SESSION['current_image'])){
unlink($_SERVER['DOCUMENT_ROOT']."/uploadfiles/users/student-img/".$_SESSION['current_image']);
unset($_SESSION['current_image']);
}
echo '<script>';
echo 'alert("User removed successfully.");';
echo 'window.location.href = "'.base_url('account/view-user/').'";';
echo '</script>';
} else {
echo '<script>';
echo 'alert("Error while removing. Deleting user unable to processed.");';
echo 'window.location.href = "'.base_url('account/view-user/').'";';
echo '</script>';
}
}
}
My model function to delete user :
function deleteUser($selectedId){
// first check either user have posted blog
$this->db->select('user_id');
$this->db->from('blog_content');
$this->db->where('user_id', $selectedId);
$query = $this->db->get();
$r = $query->row();
if(!empty($r)){
$this->db->delete('users_student, blog_content');
$this->db->from('users_student, blog_content');
$this->db->where('blog_content.user_id = users_student.id');
$this->db->where('users_student.id',$selectedId);
if($this->db->affected_rows()){
return true;
} else { return false; }
} else {
$this->db->delete('users_student');
$this->db->where('id',$selectedId);
if($this->db->affected_rows()){
return true;
} else { return false; }
}
}
In your deleteUser function, replace this code:
$this->db->delete('users_student, blog_content');
$this->db->from('users_student, blog_content');
$this->db->where('blog_content.user_id = users_student.id');
$this->db->where('users_student.id',$selectedId);
with this:
$this->db->delete('blog_content', array('user_id' => $selectedId));
$this->db->delete('users_student', array('id' => $selectedId));
I have solved my issue. It is the Codeigniter query format to delete.
Note : In Codeigniter delete query, specify WHERE first before DELETE
function deleteUser($selectedId){
// first check either user have posted blog
$this->db->select('user_id');
$this->db->from('blog_content');
$this->db->where('user_id', $selectedId);
$query = $this->db->get();
$r = $query->row();
if(!empty($r)){
// delete from blog first
$this->db->where('user_id',$selectedId);
$this->db->delete('blog_content');
if($this->db->affected_rows()){
// then delete from user
$this->db->where('id',$selectedId);
$this->db->delete('users_student');
if($this->db->affected_rows()){
return true;
} else { return false; }
}
} else {
$this->db->where('id',$selectedId);
$this->db->delete('users_student');
if($this->db->affected_rows()){
return true;
} else { return false; }
}
}

fat models and thin controllers in codeigniter

this is a user.php controller
public function verifyLogin() {
if (isset($_POST["email"])) {
$e = $this->input->post("email");
$p = $this->input->post("pass");
$this->form_validation->set_rules("email", "email", "required|valid_email|xss_clean");
$this->form_validation->set_rules("pass", "password", "required|xss_clean");
if ($this->form_validation->run()) {
$data = array(
'select' => '*',
'table' => 'users',
'where' => "email = '$e' AND activated = '1'"
);
$checklogin = $this->query2->selectData($data);
if ($checklogin === FALSE) {
echo "quering userInfo fails. email is wrong or activation not done";
exit();
} else {
foreach ($checklogin as $row) {
$dbid = $row->id;
$dbusername = $row->username;
$dbpassword = $row->password;
$dbemail = $row->email;
if ($p === $dbpassword) {
$login_data = array(
'name' => $dbusername,
'email' => $dbemail,
'password' => $dbpassword,
'id' => $dbid,
'expire' => '86500',
'secure' => TRUE,
'logged_in' => TRUE
);
$this->input->set_cookie($login_data);
$this->session->set_userdata($login_data);
if ($this->session->userdata("logged_in")) {
$time = time();
$now = unix_to_human($time, TRUE, 'us');
$updateLogin = $this->query1->updateLogin($e, $now);
if ($updateLogin) {
echo "success";
} else {
echo 'update failed';
}
} else {
echo "session failed";
}
}else{
echo 'password incorrect';
}
}
}
} else {
echo "form validation fails";
}
} else {
$this->load->view('header');
$this->load->view('login');
$this->load->view('modal');
$this->load->view('footer');
}
}
this is model.php
public function selectData($data){
if(isset($data['direction'])){
$dir = $data['direction'];
}else{
$dir = "ASC";
}
if(isset($data['offset'])){
$off = $data['offset'];
}else{
$off = '0';
}
if(isset($data['select']) && isset($data['table'])){
$this->db->select($data['select'])->from($data['table']);
}
if(isset($data['where'])){
$this->db->where($data['where']);
}
if(isset($data['order_by_name'])){
$this->db->order_by($data['order_by_name'], $dir);
}
if(isset($data['limit'])){
$this->db->limit($data['limit'], $off);
}
$query = $this->db->get();
if($query){
$d = $query->result();
return $d;
}else{
return FALSE;
}
}
is this a good way of quering database?
i am new to mvc and i am reading everywhere about "fat models and this controllers"
what can be done to make it a good mvc architecture?
its only acceptable to echo out from the controller when you are developing:
if ($checklogin === FALSE) {
echo "quering userInfo fails.
if checking login is false then either show a view or go to a new method like
if ($checklogin === FALSE) {
$this->showLoginFailed($errorMessage) ;
the check login code in the controller is a great example of something that could be refactored to a model. then if you need to check login from another controller its much easier. putting the form validation code in a model would be another choice. often times when you are validating form code you are also inserting/updating to a database table -- so having all those details together in a model can make things easier long term.
"fat model" does not mean one method in a model that does a hundred things. it means the controller says -- did this customer form validate and insert to the database? yes or no? 3 lines of code.
the model has the code that is looking into the "fat" details of the form, validation, database, etc etc. say 50 or more lines compared to the 3 in the controller. but the methods in the model should still be clean: small and specific.

Codeigniter Displaying Information In A View?

I'm extracting two different sets of data from a function in my model (syntax below). I'm trying to display the data my view. I put the variable in var_dump and var_dump is displaying the requested information but I'm having a hard time accessing that information. I'm getting two different sets of error messages as well. They are below. How would I display the information in my view? Thanks everyone.
Site Controller
public function getAllInformation($year,$make,$model)
{
if(is_null($year)) return false;
if(is_null($make)) return false;
if(is_null($model)) return false;
$this->load->model('model_data');
$data['allvehicledata'] = $this->model_data->getJoinInformation($year,$make,$model);
$this->load->view('view_show_all_averages',$data);
}
Model_data
function getJoinInformation($year,$make,$model)
{
$data['getPrice'] = $this->getPrice($year,$make,$model);
$data['getOtherPrice'] = $this->getOtherPrice($year,$make,$model);
return $data;
}
function getPrice($year,$make,$model)
{
$this->db->select('*');
$this->db->from('tbl_car_description d');
$this->db->join('tbl_car_prices p', 'd.id = p.cardescription_id');
$this->db->where('d.year', $year);
$this->db->where('d.make', $make);
$this->db->where('d.model', $model);
$query = $this->db->get();
return $query->result();
}
function getOtherPrice($year,$make,$model)
{
$this->db->select('*');
$this->db->from('tbl_car_description d');
$this->db->where('d.year', $year);
$this->db->where('d.make', $make);
$this->db->where('d.model', $model);
$query = $this->db->get();
return $query->result();
}
View
<?php
var_dump($allvehicledata).'<br>';
//print_r($allvehicledata);
if(isset($allvehicledata) && !is_null($allvehicledata))
{
echo "Cities of " . $allvehicledata->cardescription_id . "<br />";
$id = $allvehicledata['getPrice']->id;
$model = $allvehicledata[0]->model;
$make = $allvehicledata->make;
echo "$id".'<br>';
echo "$make".'<br>';
echo "$model".'<br>';
echo $allvehicledata->year;
}
?>
Error Messages
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: views/view_show_all_averages.php
Line Number: 7
A PHP Error was encountered
Severity: Notice
Message: Undefined offset: 0
Filename: views/view_show_all_averages.php
Line Number: 9
In your controller you are assigning the result of function getJoinInformation to the variable allvehicledata. This variable is then assigned to the view.
The function getJoinInformation is returning an array with the following
$data = array(
'getPrice' => $this->getPrice($year,$make,$model),
'getOtherPrice' => $this->getOtherPrice($year,$make,$model)
);
So in your view you can access the attributes getPrice and getOtherPrice in the object $allvehicledata like
$allvehicledata->getPrice;
$allvehicledata->getOtherPrice;
In line 7 you try to access the attribute cardescription_id, which is not an attribute of the object $allvehicledata.
I think this is an attribute which is get from the db query, so you should try to access it allvehicledata->getPrice->cardescription_id or allvehicledata->getOtherPrice->cardescription_id.
In line 9 you try to access some data stored in an array $model = $allvehicledata[0]->model;, but $allvehicledata is not an array.

simple codeigniter query + results display won't display

I'm trying to display data from my database in a Codeigniter view. Seems like it should be simple, but it's just not working.
I'm getting 2 errors: undefined variable ($movielist, in the view) and invalid argument for php foreach, also in the view.
Any idea how I can get this to work? Code below.
Controller
function displayMovies() {
$this->load->model('movie_list_model');
$data['movielist'] = $this->movie_list_model->getList();
$this->load->view('movielist_view', $data);
}
Model
function getList() {
$query = $this->db->query('SELECT firstname, lastname, favorite_movie FROM movies');
return $query->result();
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row)
{
echo $row['firstname'];
echo $row['lastname'];
echo $row['favorite_movie'];
}
}
View
<?php foreach($movielist as $mlist)
{
echo $mlist->firstname . '<br />';
echo $mlist->lastname . '<br />';
echo $mlist->favorite_movie;
}
?>
If( the query doesn't find any rows, it will return null, resulting in the undefined error in your view. The invalid argument error is because you can't iterate through null.
A safety would be including something like this in your view:
if($movielist)
{
/* foreach() {} */
}
Also, your model should only return data (not echo it).
function getList() {
$query = $this->db->query('SELECT firstname, lastname, favorite_movie FROM movies');
return $query->result(); /* returns an object */
// Alternatively:
// return $query->result_array(); /* returns an array */
}
I also recommend using Active record:
function getList() {
$this->db->select('firstname');
$this->db->select('lastname');
$this->db->select('favorite_movie');
$query = $this->get('movies');
return $query->result();
}
Good luck!