How to save data as array in laravel - laravel

I have some of the data, I want to save my data-id in array format. How can I do this? Below is my controller code.
Controller:
public function PostSaveRentCertificateReport(Request $request)
{
$report = $request->session()->get('report');
$reports = new Report;
$reports->column_one = $report->sum('column_one');
$reports->column_two = $report->sum('column_two');
// I want to save those id as array
$reports->adc_report_id = array('$report->id');
$reports->save();
$notification = array(
'message' => 'Report Created Successfully',
'alert-type' => 'success'
);
return redirect()->route('adc.pending.reports')->with($notification);
}

You can encode the data as JSON before saving it.
$reports = new Report;
$reports->column_one = $report->sum('column_one');
$reports->column_two = $report->sum('column_two');
$reports->adc_report_id = json_encode([$report->id]);
$reports->save();
But this will make it a bit more difficult to work with.

Related

CodeIgniter 3 code does not add data to database into 2 different tables (user_info & phone_info)

The problem is when I entered a new name no data is added. A similar thing happen when I entered an already existing name. Still, no data is added to the database. I am still new to CodeIgniter and not entirely sure my query builder inside the model is correct or not.
In the Model, I check if the name already exists insert data only into the phone_info table. IF name does not exist I insert data into user_info and phone_info.
Controller:
public function addData()
{
$name = $this->input->post('name');
$contact_num = $this->input->post('contact_num');
if($name == '') {
$result['message'] = "Please enter contact name";
} elseif($contact_num == '') {
$result['message'] = "Please enter contact number";
} else {
$result['message'] = "";
$data = array(
'name' => $name,
'contact_num' => $contact_num
);
$this->m->addData($data);
}
echo json_encode($result);
}
Model:
public function addData($data)
{
if(mysqli_num_rows($data['name']) > 0) {
$user = $this->db->get_where('user_info', array('name' => $data['name']))->result_array();
$user_id = $user['id'];
$phone_info = array(
'contact_num' => $data['contact_num'],
'user_id' => $user_id
);
$this->db->insert('phone_info',$phone_info);
} else {
$user_info = array(
'name' => $data['name']
);
$this->db->insert('user_info', $user_info);
$user = $this->db->get_where('user_info', array('name' => $data['name']))->result_array();
$user_id = $user['id'];
$phone_info = array(
'contact_num' => $data['contact_num'],
'user_id' => $user_id
);
$this->db->insert('phone_info', $phone_info);
}
}
DB-Table user_info:
DB-Table phone_info:
Extend and change your model to this:
public function findByTitle($name)
{
$this->db->where('name', $name);
return $this->result();
}
public function addData($data)
{
if(count($this->findByTitle($data['name'])) > 0) {
//.. your code
} else {
//.. your code
}
}
Explanation:
This:
if(mysqli_num_rows($data['name']) > 0)
..is not working to find database entries by name. To do this you can use codeigniters built in model functions and benefit from the MVC Pattern features, that CodeIgniter comes with.
I wrapped the actual findByName in a function so you can adapt this to other logic and use it elswehere later on. This function uses the query() method.
Read more about CodeIgniters Model Queries in the documentation.
Sidenote: mysqli_num_rows is used to iterate find results recieved by mysqli_query. This is very basic sql querying and you do not need that in a MVC-Framework like CodeIgniter. If you every appear to need write a manual sql-query, even then you should use CodeIgniters RawQuery methods.

Attach TCPDF to mail in Laravel

I want to attach pdf generated with tcpdf library without save.
I'm able to attach the pdf generated but it's corrupt.
I search a lot examples but any seems don't work
This my code:
public function index($id) {
$viaje = Viaje::find($id);
$users = User::orderBy('id', 'asc')->get();
// usersPdf is the view that includes the downloading content
$view = \View::make('usersPdf', ['viaje' => $viaje, 'users' => $users]);
$html_content = $view->render();
// Set title in the PDF
PDF::SetTitle("List of users");
PDF::AddPage();
PDF::writeHTML($html_content, true, false, true, false, '');
//PDF::Output('userlist.pdf');
$fileatt = PDF::Output($name='yourfilename.pdf', $dest='E');
$pdf = chunk_split($fileatt);
$contactopro = Contactoviajespro::find($id);
$data = [
'link' => 'http://',
'contacto' => $contactopro->name,
];
Mail::send('emails.notificacion', $data, function($msg) use($pdf) {
$msg->from('administracion#buendialogistica.com', 'Javier');
$msg->to('xavieeee#gmail.com')->subject('Notificación');
$msg->attachData($pdf, 'orden.pdf');
});
return redirect()->route('home')
->with(['message' => 'Email enviado correctamene']);
}
Use "S" to generate pdf and do not do chunk_split(), Laravel will do that. Additionally, if you are using queue() instead of send(), it will fail because of the attachment. To queue, write a job and send with the job queue.

new created model with related table output and then to json

How do get the related user table of a newly created Contact model and then in the response header content-length out put it toJson().
public function store(Request $request) {
try {
$contact = new Contact();
$contact->email_address = Helper::strip_tags($request->get('email_address'));
$contact->firstname = ucfirst($request->get('firstname'));
$contact->lastname = ucfirst($request->get('lastname'));
$contact->company = ucfirst($request->get('company'));
$contact->phone = $request->get('phone');
$contact->mobile = $request->get('mobile');
$contact->description = Helper::strip_tags($request->get('description'));
if($contact->save()) {
// here is the part I'm having trouble with
$contact = $contact->with('user')->get();
return response()->json($contact, 200, ['Content-Length' => strlen($contact->toJson())]);
} else {
return response()->json(array('error' => true, 'messages' => $contact->errors), 400);
}
} catch(Exception $e) {
return response()->json(array('error' => true, 'type' => 'exception', 'message' => $e->getMessage()), 500, ['Content-Length' => $e->getMessage()]);
}
As you already have the model loaded (when you created it) you wouldn't use with() as it is for eager loading relationships.
If I understand you question correctly, to get the User relationship included in the output you would instead use lazy eager loading which would look like:
$contact->load('user');

Saving Model data to database

I have a Report Model which is like the following.
class Report extends Model
{
protected $table = 'reports';
protected $guarded = [];
public function leadsCollection()
{
return $this->hasMany('App\ReportModels\LeadsCollection');
}
}
A Report can have many LeadsCollection, its Model is the following.
class LeadsCollection extends Model
{
protected $table = 'leadsCollection';
protected $guarded = [];
private $xmlElement;
public function __construct($xmlElement = null, $attributes = array()) {
parent::__construct($attributes);
$this->xmlElement = $xmlElement;
}
public function report()
{
return $this->belongsTo('App\ReportModels\Report');
}
function asArray(){
$reportItem = array();
foreach($this->xmlElement->Leads->Lead as $lead) {
$dateIdentified = date("d/m/Y", strtotime($lead->Date));
$reportItem[] = array(
'LeadID' => (string)$lead->ID,
'Client' => (string)$lead->Client->Name,
'Category' => (string)$lead->Category,
'DateIdentified' => $dateIdentified,
'LeadName' => (string)$lead->Name,
'Owner' => (string)$lead->Owner->Name
);
}
return $reportItem;
}
}
Now I am trying to save some data to a database. So I get a list of all Leads by calling my LeadsCollection and passing it an XML list of Leads.
I then loop these Leads and add it to an array. At the same time however I need to save it to the database. This is what I have so far.
public function getForecastReportForLeads() {
$leads = new LeadsCollection(new \SimpleXMLElement(Helper::getCurrentLeads()));
$reportArray = array();
foreach ($leads->asArray() as $lead) {
$report = new Report();
$report->reportName = 'Lead Forecast';
if($report->save()) {
$leads->leadId = $lead['LeadID'];
$leads->leadCategory = $lead['Category'];
$leads->dateIdentified = $lead['DateIdentified'];
$leads->leadName = $lead['LeadName'];
$leads->owner = $lead['Owner'];
$leads->client = $lead['Client'];
$leads->report_id = $report->id;
$leads->save();
$reportItem = array(
'leadData' => $lead
);
$reportArray[] = $reportItem;
}
}
return $reportArray;
}
So I create the Report item, and within the database if I have 7 Leads I end up with 7 Report rows within my reports table, as it should be. However, when I save the Leads, I only end up with 1 row in my leadsCollection table, every other entry seems to be overridden. I think this is because I am not creating the Lead Object within the loop. However, I cant really create it within the loop because I need to loop whats returned when I first create it.
Not sure how clear I am but is there anything I can add to my Model so I can stop any overriding? Or do I need to do this another way?
Thanks
Either you get the variable inside the save method or initialize the new
$report = new Report($reportItem);
$report->save($report)
I'm having a similar Issue right, let me show my code. It would work for your case. My bug is that I'm updating and the plan_detail.id gets moved instead of creating a new one. But if you create would be fine:
public function store(Request $request)
{
$this->validate($request, [ 'title' => 'required',
'description' => 'required']);
$input = $request->all();
$plan_details = Plan_Detail::ofUser()->get();
$plan = new Plan($request->all());
DB::beginTransaction();
Auth::user()->plans()->save($plan);
try {
foreach ($plan_details as $k => $plan_detail)
Plan::find($plan['id'])->details()->save($plan_detail);
DB::commit();
} catch (Exception $e) {
Log::error("PGSQL plan detail " . $e->message());
DB::rollback();
session()->flash('message', 'Error al guardar el plan de entreno');
}
return redirect('plans');
}

Symfony3 error changing DateTime on entity with Ajax

I want to change the date of a doctrine entity but the change is not saved.
With ajax a call this function:
public function relancerTicketAction(Request $request, $id)
{
if (!$this->get('session')->get('compte'))
return $this->redirect($this->generateUrl('accueil'));
$isAjax = $request->isXMLHttpRequest();
if ($isAjax)
{
$ticket = $this->getDoctrine()->getManager()->getRepository('CommonBundle:Ticket')->find($id);
$ticket->setDateButoire($ticket->getDateButoire()->modify('+7 day'));
$this->getDoctrine()->getManager()->flush();
$response = array("code" => 100, "success" => true, 'date' => $ticket->getDateButoire()->format('d-m-Y'));
return new Response(json_encode($response));
}
$response = array("code" => 0, "success" => false);
return new Response(json_encode($response));
}
When I alert the result I get the right new value, but after reload there is no change saved.
This function called in the same conditions works:
public function traiterTicketAction(Request $request, $id)
{
if (!$this->get('session')->get('compte'))
return $this->redirect($this->generateUrl('accueil'));
$isAjax = $request->isXMLHttpRequest();
if ($isAjax)
{
$compte = $this->getDoctrine()->getManager()->getRepository('CommonBundle:Compte')->find($this->get('session')->get('compte')->getId());
$ticket = $this->getDoctrine()->getManager()->getRepository('CommonBundle:Ticket')->find($id);
$ticket->addDestinataire($compte);
$this->getDoctrine()->getManager()->flush();
$response = array("code" => 100, "success" => true);
return new Response(json_encode($response));
}
$response = array("code" => 0, "success" => false);
return new Response(json_encode($response));
}
see the docs
When calling EntityManager#flush() Doctrine computes the changesets of
all the currently managed entities and saves the differences to the
database. In case of object properties (#Column(type=”datetime”) or
#Column(type=”object”)) these comparisons are always made BY
REFERENCE. That means the following change will NOT be saved into the
database:
/** #Entity */
class Article
{
/** #Column(type="datetime") */
private $updated;
public function setUpdated()
{
// will NOT be saved in the database
$this->updated->modify("now");
}
}
So, in your case I suggest to clone dateButoire, like this
$ticket = $this->getDoctrine()->getManager()->getRepository('CommonBundle:Ticket')->find($id);
$newDateButoire = clone $ticket->getDateButoire();
$ticket->setDateButoire($newDateButoire->modify('+7 day'));
$this->getDoctrine()->getManager()->flush();

Resources