if clauses not working in laravel 5.3 mailable - email

in Laravel 5.1 I sent message like this. So user could send message with or without attachment.
Mail::send('emails.contacts', $mailarray, function($message) use ($mailarray) {
$message->from($mailarray['email'], $mailarray['name'] );
$message->to('admin#site.ru', 'admin');
$message->setCc($mailarray['email'], $mailarray['name']);
$message->replyTo($mailarray['email'], $mailarray['name'] );
$message->subject('Письмо со страницы Контакты');
if ( isset($mailarray['attachment']) )
{
$message->attach($mailarray['attachment']->getRealPath(), array(
'as' => $mailarray['attachment']->getClientOriginalName(),
'mime' => $mailarray['attachment']->getMimeType()));
}
});
This approach is not working with Mailable. Doing this I get error
syntax error, unexpected 'if' (T_IF)
And it is working only like this, which is duplicating code a lot.
public function build()
{
if (is_null($this->file) ) {
return $this->subject('Обратный звонок с сайта')
->view('emails.callback')
->cc($this->input['email'], $this->input['name'])
->replyTo($this->input['email'], $this->input['name']);
}
else {
return $this->subject('Обратный звонок с сайта')
->view('emails.callback')
->cc($this->input['email'], $this->input['name'])
->replyTo($this->input['email'], $this->input['name'])
->attach($this->file, array('as' => $this->file->getClientOriginalName(), 'mime' => $this->file->getClientMimeType() ));
}
}

Related

Codeigniter Rest Api Delete using parameter ID

I'm Learning CRUD operation with Codeigniter and Rest Api for my app Flutter.But I'm get some problem with Delete operation. I'm want delete data using parameter ID , but the message show me ID Null.
It's my Get Operation using parameter
http://192.168.43.159/wpu-rest-server/apii/mahasiswa/get?id=5
Possible i'm make delete operation like this ?
http://192.168.43.159/wpu-rest-server/apii/mahasiswa/delete?id=5
I already try
http://192.168.43.159/wpu-rest-server/apii/mahasiswa/delete/5
http://192.168.43.159/wpu-rest-server/apii/mahasiswa/delete/id/5
But Nothing change , still ID null.
It's my Controller And Model Rest Api :
Controller
public function delete_delete()
{
$id = $this->delete('id');
$msgDelete = ['id' => $id, 'message' => 'Deleted the resource'];
$msgEmpty = ['status' => false, 'message' => 'ID Not Found'];
$msgBadRequest = ['status' => false, 'message' => 'Provide an ID'];
if ($id === null) {
$this->set_response($msgBadRequest, 400);
} else {
if ($this->mahasiswa->deleteMahasiswa($id) > 0) {
$this->set_response($msgDelete, 204);
} else {
$this->set_response($msgEmpty, 404);
}
}
}
Model
public function deleteMahasiswa($id)
{
$this->db->delete('mahasiswa', ['id' => $id]);
return $this->db->affected_rows();
}
I am seeing some ambigius things in your code for example the api url is :
http://192.168.43.159/wpu-rest-server/apii/mahasiswa/delete/5
and your controller method name is delete_delete .
If you are using the get method you should respect the following :
base_url/controller_name/method_name?id=3
and then you can get the value with :
$this->input->get('id')
otherwise if you are passing the id as a method argument like the following :
http://your_domain/controller_name/delete/5
you can get the value like this :
class controller_name extends CI_Controller {
.
.
.
public function delete($id=null){
}
}
If Possible do like this
192.168.43.159/wpu-rest-server/apii/mahasiswa/delete_delete?id=5
Controller
public function delete_delete() {
$id = $this->input->get('id');
$this->mahasiswa->deleteMahasiswa($id);
redirect('http://192.168.43.159/wpu-rest-server/apii/mahasiswa');
}
Model
function deleteMahasiswa() {
$this->db->where('id', $id);
$this->db->delete('mahasiswa');
}

CodeIgniter Suddenly Cannot Upload Image and says Cannot Be Null

Greeting everyone and especially to Senior of CodeIgniter Developer.
I have a problem with website that was built from CodeIgniter (I am not the developer inherited by previous epmployer). This website cannot working properly, especially when upload the image and shows warning about
Error Number: 1048 Column 'article_image' cannot be null
I did try with find the problem on the script and database, but nothing change and because no one change the codes & contents. Today, i try again with changing the "Null into yes" (previously is "No"), and tried to upload the article. It is miracle that it is working but the next problem is the image is gone (broken). I search at other and looking people with same problem with me says that i need to upgrade the CodeIgniter. Mine is 3.0.0 while the latest is 3.1.10. I copy paste the content inside /System and /views/error/cli not making better but make it worse, the image at the web page is gone(missing).
This is my Article_model
defined('BASEPATH') OR exit('No direct script access allowed');
class Article_model extends CI_Model {
public function get_all()
{
// $this->db->order_by('article_date', 'desc');
// $this->db->order_by('article_view', 'desc');
// $query = $this->db->get_where('article', array('flag !=' => 3));
// return $query->result_array();
$query = $this->db->query("SELECT A.*,B.*, A.id AS id_article FROM article AS A JOIN category B ON A.article_category = B.id WHERE A.flag != 3 ORDER BY article_date DESC, article_view DESC ");
return $query->result_array();
}
public function check($article_id)
{
$query = $this->db->get_where('article', array('flag !=' => 3, 'id' => $article_id));
return $query->row_array();
}
public function get_category()
{
$query = $this->db->order_by('category_name', 'ASC')->get_where('category', array('flag' => 1));
return $query->result_array();
}
public function get_tag()
{
$query = $this->db->order_by('tag_name', 'ASC')->get_where('tag', array('flag' => 1));
return $query->result_array();
}
public function get_selected_tag($article_id)
{
$query = $this->db
->select('tag.id, tag_name')
->join('article_tag', 'tag_id = tag.id')
->where(array('tag.flag' => 1, 'article_id' => $article_id))
->get('tag');
return $query->result_array();
}
public function insert()
{
$this->load->helper('upload');
$this->load->library('image_moo');
$image = file_upload('article_image', 'upload/article');
$this->image_moo->load($image['full_path']);
$this->image_moo->resize(924, 527)->save($image['path'] . '/' . $image['file_name'], TRUE);
$this->image_moo->resize_crop(100, 69)->save($image['path'] . '/thumb/' . $image['file_name']);
$this->image_moo->resize_crop(367, 232)->save($image['path'] . '/cover/' . $image['file_name']);
$insert_data = array(
'article_author' => $this->session->admin_id,
'article_title' => $this->input->post('article_title'),
'article_slug' => url_title($this->input->post('article_title'), '-', TRUE),
'article_category' => $this->input->post('article_category'),
'article_image' => $image['file_name'],
'article_content' => $this->input->post('article_content'),
'is_popup' => $this->input->post('is_poup'),
'article_date' => $this->input->post('article_date'),
);
$this->db->insert('article', $insert_data);
$article_id = $this->db->insert_id();
foreach ($this->input->post('article_tag') as $tag)
{
// Check apakah tag itu udah ada di database?
if (is_numeric($tag))
{
$tag_id = $tag;
}
else
{
$this->db->insert('tag', array('tag_name' => strtolower(trim($tag)), 'tag_slug' => url_title(trim($tag), '-', TRUE)));
$tag_id = $this->db->insert_id();
}
if ( ! $this->db->get_where('article_tag', array('article_id' => $article_id, 'tag_id' => $tag_id))->row_array())
{
$this->db->insert('article_tag', array('article_id' => $article_id, 'tag_id' => $tag_id));
}
}
}
public function update($id)
{
$this->load->helper('upload');
$this->load->library('image_moo');
$image = file_upload('article_image', 'upload/article');
$this->image_moo->load($image['full_path']);
$this->image_moo->resize(924, 527)->save($image['path'] . '/' . $image['file_name'], TRUE);
$this->image_moo->resize_crop(100, 69)->save($image['path'] . '/thumb/' . $image['file_name']);
$this->image_moo->resize_crop(367, 232)->save($image['path'] . '/cover/' . $image['file_name']);
$insert_data = array(
'article_author' => $this->session->admin_id,
'article_title' => $this->input->post('article_title'),
'article_slug' => url_title($this->input->post('article_title'), '-', TRUE),
'article_category' => $this->input->post('article_category'),
'is_popup' => $this->input->post('is_popup'),
'article_content' => $this->input->post('article_content'),
'article_date' => $this->input->post('article_date'),
);
if ($image)
{
$insert_data['article_image'] = $image['file_name'];
}
$article_id = $id;
$this->db->where('id', $id);
$this->db->update('article', $insert_data);
$this->db->where('article_id', $id);
$this->db->delete('article_tag');
foreach ($this->input->post('article_tag') as $tag)
{
// Check apakah tag itu udah ada di database?
if (is_numeric($tag))
{
$tag_id = $tag;
}
else
{
$this->db->insert('tag', array('tag_name' => strtolower(trim($tag)), 'tag_slug' => url_title(trim($tag), '-', TRUE)));
$tag_id = $this->db->insert_id();
}
if ( ! $this->db->get_where('article_tag', array('article_id' => $article_id, 'tag_id' => $tag_id))->row_array())
{
$this->db->insert('article_tag', array('article_id' => $article_id, 'tag_id' => $tag_id));
}
}
}
}
What should i do guys? i did backup but it remain same like after upgraded. Thank you. Web Url (http://www.hidupseimbangku.com/)
First. If you want to upgrade CI Version you must follow Upgrading Guide one by one. There may be break changes and you need to correct them, you can find this guide here:
https://www.codeigniter.com/userguide3/installation/upgrading.html
I suggest you rollback upgrade changes and start again doing one by one. It is not hard, it is just time consuming.
The error you're getting is probably related to an error of uploading process. What is file_upload?
I also suggest you read this, for properly file upload.

Adding user input into Edited field

I want to add an edit function if user decides to change the field value but i cant seem to find the right way to do this. Ive tried searching through google but it doesn't give any answer related for this problem.
code here:
<?php
class CloseTicket
{
public function do_CloseTicket($bean, $events, $args)
{
//checks if the ticket is already in use
if(!isset($bean->fetched_row['field_name_id'])){
if (!empty($bean->field_name)) {
//if ticket status is closed then it displays an error message
$module = BeanFactory::getBean("CUSTOM MODULE", $bean->field_name_id);
if ($module->status == 'Closed') {
SugarApplication::appendErrorMessage("Ticket is already used. Please use another Ticket.");
$params = array(
'module' => 'Module',
'action' => 'ListView',
'record' => $bean->id,
);
SugarApplication::redirect('index.php?' . http_build_query($params));
//else adds the ticket then closed it
} else {
$module->status = "Closed";
$module->save();
}
}
//if ticket is already taken then it display an error message
} else {
SugarApplication::appendErrorMessage("Ticket is already attached.");
$params = array(
'module' => 'module',
'action' => 'ListView',
'record' => $bean->id,
);
SugarApplication::redirect('index.php?' . http_build_query($params));
}
}
}
I can't fully understand your issue.
But if you are trying to edit the duplicated related bean the params should be EditView instead of ListView like this:
$params = array(
'module' => 'Module',
'action' => 'EditView',
'record' => $bean->id,
);
SugarApplication::redirect('index.php?' . http_build_query($params));

Validation error messages as JSON in Laravel 5.3 REST

My app is creating a new entry via a POST request in an api end point.
Now, if any validation is failed then instead of returning an error json, laravel 5.3 is redirecting the request to home page.
Here is my controller:
public function create( Request $request )
{
$organization = new Organization;
// Validate user input
$this->validate($request, [
'organizationName' => 'required',
'organizationType' => 'required',
'companyStreet' => 'required'
]);
// Add data
$organization->organizationName = $request->input('organizationName');
$organization->organizationType = $request->input('organizationType');
$organization->companyStreet = $request->input('companyStreet');
$organization->save();
return response()->json($organization);
}
If there is no issue with validation then the entity will be successfully added in the database, but if there is issue with validating the request then instead of sending all the error messages as a json response it redirects back to the home page.
How i can set the validate return type to json, so with every request if the validation failed then laravel will send all the error messages as json by default.
You can do your validation as:
$validator = \Validator::make($request->all(), [
'organizationName' => 'required',
'organizationType' => 'required',
'companyStreet' => 'required'
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 422)
}
The validation used in the question looks as per the recommendation by laravel. The reason of redirection is that it throws an exception which you can easily catch using the code below. So it's better to use the recommended way of code instead of re-writing framework's code again :)
public function create( Request $request )
{
$organization = new Organization;
// Validate user input
try {
$this->validate($request, [
'organizationName' => 'required',
'organizationType' => 'required',
'companyStreet' => 'required'
]);
} catch (ValidationException $e) {
return response()->json($e->validator->errors(), 422);
}
// Add data
$organization->organizationName = $request->input('organizationName');
$organization->organizationType = $request->input('organizationType');
$organization->companyStreet = $request->input('companyStreet');
$organization->save();
return response()->json($organization, 201);
}

Pass Eloquent Model As An Closure Argument In PHP

I'm using Laravel Illuminate/Database outside of laravel application. I'm trying to pass the Eloquent model as my closure argument but its throwing an error. May be I'm passing it wrongly. My code is as following:
// Create a dummy subject (This is working absolutely fine)
SubjectModel::create(array(
'title' => 'Mathematics',
'description' => 'Math Subject',
'slug' => 'math',
'ka_url' => 'http://khanacademy.org/math'
));
$scrapper = new SubjectScrapper();
$scrapper->setUrl('');
This is not working. SubjectModel is not being passed in the following closure
$scrapper->runScrapper(function($subjects) use ($scrapper, SubjectModel $subjectModel) {
if(!empty($subjects))
{
foreach ($subjects as $subject) {
$urlParts = explode('/', $subject['url']);
$slug = end($urlParts);
$subjectModel::create(array(
'title' => $subject['subject_name'],
'slug' => $slug,
'ka_url' => $scrapper->getBaseUrl().$subject['link'],
));
}
}
});
Could anybody please tell me how to accomplish this task.
Try this. No need to pass object in closure
$scrapper = new SubjectScrapper();
$scrapper->setUrl('');
$scrapper->runScrapper(function($subjects) use ($scrapper, $output) {
SubjectModel::create(array(
'title' => 'Math',
'slug' => 'math',
'ka_url' => 'http://math'
));
$output->writeln('<info>Total Subjects Scrapped:: '.count($subjects).'</info>'.PHP_EOL);
});