I am using a modelless form to send a contact email. I am using the example in the cookbook.
With the change to data in objects form arrays I am unsure what form the data is in being passed to the ContactForm.php
I have tried $data['name'] and $data[0]['name']
View for input name without the data[]
<input type="text" class="form-control" name="name" placeholder="Your Name" required="" aria-required="true" aria-invalid="false">
PagesController.php
public function contact(){
$this->request->allowMethod('ajax');
$contact = new ContactForm();
if ($this->request->is('post')) {
if ($contact->execute($this->request->data)) {
$data = array(
'status' => 'successful'
);
} else {
$data = array(
'status' => 'error'
);
}
$this->set(compact('data')); // Pass $data to the view
$this->set('_serialize', 'data');
}
}
ContactForm.php
protected function _execute(array $data)
{
// Send an email.
$email = new Email('default');
$email->emailFormat('html');
$email->template('demoTemplate')->viewVars( array('userName' => $data[0]['name'],
'userCompany' => '$data',
'userEmail' => '$data',
'userPhone' => '$data'));
$email->from('info#domain.com');
$email->to('$data');
$email->bcc('$data');
$email->subject('Contact Form Submission');
if ($email->send()) {
return true;
}
else {
return false;
}
}
Well for do this I use first this tool advanced-rest-client, and inside the code of cakephp you can use try and catch, you can user debug() too, example debug($data); in combination with advanced-rest-client you can see the result.
and if debug dont work serialice the data
$this->set('data', $data);
$this->set('_serialize', ['data']);
but even when serialized data use advanced-rest-client, just select the post option and type the url of where you want to get the post.
so:
public function contact(){
$this->request->allowMethod('ajax');
$contact = new ContactForm();
if ($this->request->is('post')) {
if ($contact->execute($this->request->data)) {
debug($this->request->data());//first
$datos = $this->request->data();//second
$data = [
'content' => $datos,
'status' => 'successful',
];
} else {
$datos = $this->request->data();
$data = [
'content' => $datos,
'status' => 'error,
];
}
$this->set(compact('data')); // Pass $data to the view
$this->set('_serialize', 'data');
}
}
Related
I am trying to make the value of $input data to first match with one the pluck array values in a user table in the database before the input is saved and a response of 'its a match be given'. I trying to put these checks on an API I'm making. I'm new to laravel API and I will appreciate the help. Thank you
public function create(Request $request)
{
//
$this->validate($request, [
'inputed_number' => 'required|unique:users',
'user_id' => 'required'
]);
try {
Auth::user();
$phonenumber = new PhoneNumber();
$phonenumber->inputed_number = $request->inputed_number;
$phonenumber->user_id = $request->user_id;
if($this->user->phonenumber()->save($phoneuumber)){
$user = User::all();
$input = $request->only('inputed_number');
$user_number = $user->pluck('phone');
foreach ($input as $phone) {
if ($phone !== $user_number) {
return response()->json([
'success' => false,
'message' => 'Invalid number',
'data' => $phone,
], Response::HTTP_UNAUTHORIZED);
}
return response()->json([
'success' => true,
'message' => 'Its a match!!',
'data' => $phone,
]);
}
}
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => 'You have already inputted this number.',
], Response::HTTP_UNAUTHORIZED);
}
}
just get the whole user object with Auth:user no need for the pluck statement, you can access values directly via user object,
$user = Auth:user();
$input = $request->only('inputed_number');
if($user->phone !== $input ) {
//perform this code
}
If you want to match phone numbers from all users,
//get all users where phone number matches
$users = User::where('phone', $input)->get();
// iterate through $users rows
foreach ($users as $user) {
///do some thing
}
Hi I am trying to update a record in my database, It is a reservation that the user can update some or all of the fields and after I press submit it redirects me to the page I need but no changes happen in the database.
Model
public function res_form_input(){
$newDate = date("Y-m-d",strtotime($this->input->post('re_date')));
$newTime = date("H:i", strtotime($this->input->post('re_time')));
$data = array(
'num' => $this->input->post('num'),
'location' => $this->input->post('location'),
'diners' => $this->input->post('diners'),
're_date' => $newDate,
're_time' => $newTime,
'phonenumber' => $this->input->post('phonenumber'),
'fullname' => $this->input->post('fullname'),
);
return $data;
}
public function update_res($id){
$data = $this->res_form_input();
// $this->db->set('$data');
$this->db->where('id', $id);
$this->db->update('tables', $data);
}
Controller
public function edit() {
echo $id = $this->session->flashdata('reservation_id');
$this->Hosting_model->update_res($id);
redirect(base_url("/hosting/tableMap"));
}
I am novice to laravel.I need to send email to all the records in the table using where condition(where exam_id=1). Each record will get the email message is name and email of its own.Already stored in the table.Can any own suggest for this?
Advance thanks
public function sendmail(Request $request) {
$email = DB::table('student')->select('email','exam_id')->where('exam_id','=','1')->get();
$email= mysql_query("SELECT email FROM student WHERE exam_id='1' ;");
$title = $request->input('title');
$content = $request->input('content');
if(mysql_num_rows($email))
{
while($elist_result = mysql_fetch_array($email))
{
Mail::send('email', ['title' => $title, 'content' => $content],function ($message)
{
$message->from('dhivya#authorselvi.com', 'dhivya');
$message->to('dhivya#authorselvi.com');
$message->cc($elist_result);
$message->subject("Hello");
} );
}
}
return response()->json(['message' => 'message send successfully']);
}
public function sendmail(Request $request) {
$email = DB::table('student')->select('email','exam_id')->where('exam_id','=','1')->get();
$title = $request['title'];
$content = $request['content'];
foreach($email as $email) {
Mail::send('email', ['title' => $title, 'content' => $content],function ($message)
{
$message->from('dhivya#authorselvi.com', 'dhivya');
$message->to($email->email);
$message->subject("Hello");
});
}
return response()->json(['message' => 'message send successfully']);
}
I'm seeing that you are sticked to clear PHP and it's wrong while you are working on Laravel framework.
public function sendmail(Request $request) {
$emails = DB::table('student')->select('email','exam_id')->where('exam_id','=','1')->get();
$title = $request['title'];
$content = $request['content'];
foreach($emails as $email) {
Mail::send('email', ['title' => $title, 'content' => $content],function ($message)
{
$message->from('dhivya#authorselvi.com', 'dhivya');
$message->to($email->email);
$message->subject("Hello");
});
}
return response()->json(['message' => 'message send successfully']);
}
Take a look at your code edited by me and try it.
I've been trying to add the id of the current logged-in user into a field in my DB.
But, nothing is stored. I have tried the following methods:
public function store(StoreChildRequest $request)
{
$user = Auth::user();
$child = $request->all();
$child->merge(['user_id' => $user->id]);
$child = new Patient($child);
$child->save();
}
But the StoreChildRequest always returns the user_id is not passed.
Also this didn't work:
public function store(StoreChildRequest $request)
{
$user = Auth::user();
Input::merge(['user_id' => $user->id]);
$child = new Patient($request->all());
$child->save();
}
The same error.
Even if I try to do so with fixed data, the merge won't happen:
public function store(StoreChildRequest $request)
{
$user = Auth::user();
Input::merge(['user_id' => "01"]);
if($child = new Patient($request->all()))
{
$child->save();
return response()->json(['succes' => 'Child saved.']);
}
else
{
return response()
->json($request->getMessageBag()->toArray());
}
}
EDIT
I have noticed that when I remove the StoreChildRequest (the validation) the code works just fine. So I'm going to add the rules:
StoreChildRequest:
public function rules()
{
return [
'name' => 'required|max:255',
'givenname' => 'required|max:255',
'street' => 'required|max:255',
'streetnumber' => 'required|max:255',
'city' => 'required|max:255',
'postalcode' => 'required|digits:4',
'email' => 'required|email',
'birthdate' => 'required|date',
'sex' => 'required|max:1',
'user_id' => 'required'
];
}
The error has to be in here then?
Thank you for your help.
You could do something like this:
$user = Auth::user();
$child = $request->all();
$child['user_id'] = $user->id;
$child = new Patient($child);
$child->save();
Also, you could try:
$user = Auth::user();
$request->request->add(['user_id' => $user->id]);
$child = $request->all();
$child = new Patient($child);
$child->save();
I have created a form in Codeigniter with a phone number field that dynamically is duplicated using javascript. So basically I can have one or more fields like this.
<input name="phone[]" value=""type="text">
<input name="phone[]" value=""type="text">
Then in my controller I have
$form_data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'phone' => $this->input->post('phone[]')
);
Then I am saving this to my dabase like so
function SaveForm($form_data)
{
$this->db->insert('customers', $form_data);
if ($this->db->affected_rows() == '1')
{
return TRUE;
}
return FALSE;
}
but obviously the code for 'phone' is wrong, I just cant figure out how to properly do this.
you can't save array in to database. You can convert it in to string using implode() and whenever you needed then convert it back in array using explode(). Like below
$phone=implode(',',$this->input->post('phone'));
$form_data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'phone' => $phone
);
OR
You can convert it to json string and when you needed convert back to Array Like below:
$phone = json_encode($this->input->post('phone'));
Convert back to array
$phone = json_decode($phone, TRUE);
Modify your function as below and it will works like charm,
function SaveForm($form_data)
{
foreach ($form_data as $contact)
{
$data[] = array(
'first_name' => $contact['first_name'],
'last_name' => $contact['last_name'],
'phone' => $contact['phone']
);
}
$this->db->insert_batch('customers', $data);
if ($this->db->affected_rows() > 0)
{
return TRUE;
}
return FALSE;
}
Modified:
Oh, yes you have to edit para array that you passed to SaveForm function.
Please use following code, ignore above code:
foreach($_POST['first_name'] as $key=>$fname)
{
$form_data[] = array(
'first_name' => $_POST['first_name'][$key],
'last_name' => $_POST['last_name'][$key],
'phone' => $_POST['phone'][$key],
);
}
function SaveForm($form_data)
{
$this->db->insert_batch('customers', $data);
if ($this->db->affected_rows() > 0)
{
return TRUE;
}
return FALSE;
}
In controller
$phone = $_POST['phone'];//this will store data as array. Check image 02
$form_data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'phone' => $phone,//some times it works with '$phone'
);
In Model
function SaveForm($form_data)
{
$this->db->insert('customers', $form_data);
if ($this->db->affected_rows() == '1')
{
return TRUE;
}
else
{
return FALSE;
}
}
Tested
Image 01 (My form)
Image 02 (After Submitted)
mysql doesn’t has any array data type. So we can not store array directly into mysql database.
To do this we have to first convert array into string using php serialize() function then save it into mysql database.
for eg:php code to store array in database
$array = array("foo", "bar", "hello", "world");
$conn=mysql_connect('localhost', 'mysql_user', 'mysql_password');
mysql_select_db("mysql_db",$conn);
$array_string=mysql_escape_string(serialize($array));
To retrieve array from database
$conn=mysql_connect('localhost', 'mysql_user', 'mysql_password');
mysql_select_db("mysql_db",$conn);
$q=mysql_query("select column from table",$conn);
while($rs=mysql_fetch_assoc($q))
{
$array= unserialize($rs['column']);
print_r($array);
}
for array insertion to database use this programme in codeigniter controller=>
$inputdata=$this->input->post();
$phone=array($inputdata['phone']);
foreach($phone as $arr)
{
$phoneNo=$arr;
$f=count($phoneNo);
for($i=0;$i<$f;$i++)
{
$arre=[
'phone'=>$phoneNo[$i],
];
$insertB= $this->user_model->userdata($arre);
}
}
public function add_theme_pages(){
$page_name = $this->input->post('page');
$page_img = $this->input->post('page_img');
for($i=0; $i < count($page_name); $i++){
$pages_data = array(
'theme_id' => $this->input->post('theme_id'),
'theme_page_name' => $page_name[$i],
'theme_page_img' => $page_img[$i]
);
if($this->backendM->add_theme_pages($pages_data)){
$this->session->set_flashdata('message', 'Theme Added Successfully !');
$this->session->set_flashdata('message_class', 'green');
$this->create_template();
}else{
$this->create_template();
}
}
}