how to save pdf inside controller and pass pdf patch - laravel

pdf api -> https://github.com/barryvdh/laravel-dompdf
I create some simple API, everyone who pass some data will recaive link to pdf file.
The thing is, i dont know how to save pdf after conroller make changes inside my blade template.
so...
i already try changing data by request and that was working.
something like :
class pdfGenerator extends Controller
{
public function show(Request $request)
{
$data = $request->json()->all();
return view('test2', compact('data'));
}
}
that work well, also pdf creator works well from web.php
Route::get('/test', function () {
$pdf = PDF::loadView('test2');
return $pdf->download('test2.pdf');
});
that one just download my pdf file as expected.
but, now i try to pust some changes from request and save file but... without efford... any idea?
My code after tray to save content
class pdfGenerator extends Controller
{
public function show(Request $request)
{
$data = $request->json()->all();
return $pdf = PDF::loadView('test2', compact('data'))->save('/pdf_saved/my_test_file.pdf');
}
}
But i get only some errors. Please help :D

How can I save a PDF inside my controller and pass the PDF patch?
$data = $request->json()->all();
$pdf = app('dompdf.wrapper');
$pdf->loadView('test2', $data);
return $pdf->download('test2.pdf');

Related

Laravel Ajax controller with single route

Just wondering if this is a good way to write ajax code to interact with Laravel routes?
Example my application's require to list all customer data and also list all country through ajax. I have 3 controller ApiController, CustomerController, CountryController.
So in my routes.php I have this routes
Route::get('api/v1/ajax/json/{class}/{function}', 'Api\v1\ApiController#ajaxreturnjson');
In the ApiController.php, I have below function to call other controller function to return the data I need.
class ApiController extends Controller
{
public function ajaxreturnjson(Request $request, $controller, $function){
$input = $request->input();
if($request->input('namespace') != ''){
$namespace = $request->input('namespace');
unset($input['namespace']);
}else{
$namespace = 'App\Http\Controllers';
}
$data = array();
try {
$app = app();
$controller = $app->make($namespace.'\\'.$controller);
$data = $controller->callAction($function, array($request)+$input);
} catch(\ReflectionException $e){
$data['error'] = $e->getMessage();
}
return response()->json($data);
}
}
So example to use the ajax, I just need to pass the class name, namespace and also the function name to the ajax url.
Example to retrieve all customer info.
$.ajax({
dataType:"json",
url:"api/v1/ajax/json/CustomerController/getList",
data:"namespace=\\App\\Http\\Controllers\\",
success:function(data){
}
})
So in this way, I don't have to create so many routes for different ajax request.
But I am not sure if this will cause any security issue or is this a bad design?
Personally, I would not do it this way. Sure, you could do it this way, but it's not very semantic and debugging it could be a pain.
Also, if someone else begins working on the project, when they look at your routes file, they won't have any idea how your app is structured or where to go to find things.
I think it's better to have a controller for each Thing.

How to pass variable with a master layout in Codeiginiter

My master layout here's below and working fine. I just want little bit more passing a default variable with this master layout that I can get in every pages.
class MY_Controller extends CI_Controller {
public $layout;
function __construct() {
parent::__construct();
$this->layout='layout/master';
}
}
I need to pass variable like below:
function __construct() {
parent::__construct();
$data['msg'] = $this->session->flashdata('usermsg');
$this->layout=('layout/master',$data);
}
How do I get this.
If you are loading up the data dynamically from the controller with the help of $this->layout you can send the data like this.
Method 1:
If you are using the general method to load the data to the view you can use this method.
$this->load->view('profile_view', $data);
This will load the profile_view page along with the $data as you passs into it with the help of array()
Method 2:
If you have created a master Layout and you are passing the data from the controller to the Master Layout you need to do like this.
<?php
public function master_layout () {
$this->template['header'] = $this->load->view('include/header', $this->Front_End_data, true);
$this->template['navigation'] = $this->load->view('include/navigation', $this->Front_End_data, true);
$this->template['center'] = $this->load->view($this->middle, $this->Front_End_data, true);
$this->template['footer'] = $this->load->view('include/footer', $this->Front_End_data, true);
$this->load->view('include/index', $this->template);
?>
In this code the below line alone will be loaded dynamically based on the page which you call in the master Layout.
$this->template['center'] = $this->load->view($this->middle, $this->Front_End_data, true);
In order to pass the data to this center layout you can use the funciton like this.
$data['msg'] = 'Success';
$this->template['center'] = $this->load->view ($this->middle = 'pages/view_oage',$data, true);
$this->master_layout();
And in the page you can get the data to be printed using the foreach loop as follows.
foreach($msg as $value)
{
echo $value;
}

Simple AJAX / JSON response with CakePHP

I'm new to cakePHP. Needless to say I don't know where to start reading. Read several pages about AJAX and JSON responses and all I could understand is that somehow I need to use Router::parseExtensions() and RequestHandlerComponent, but none had a sample code I could read.
What I need is to call function MyController::listAll() and return a Model::find('all') in JSON format so I can use it with JS.
Do I need a View for this?
In what folder should that view go?
What extension should it have?
Where do I put the Router::parseExtension() and RequestHandlerComponent?
// Controller
public function listAll() {
$myModel = $this->MyModel->find('all');
if($this->request->is('ajax') {
$this->layout=null;
// What else?
}
}
I don't know what you read but I guess it was not the official documentation. The official documentation contains examples how to do it.
class PostsController extends AppController {
public $components = array('RequestHandler');
public function index() {
// some code that created $posts and $comments
$this->set(compact('posts', 'comments'));
$this->set('_serialize', array('posts', 'comments'));
}
}
If the action is called with the .json extension you get json back, if its called with .xml you'll get xml back.
If you want or need to you can still create view files. Its as well explained on that page.
// Controller code
class PostsController extends AppController {
public function index() {
$this->set(compact('posts', 'comments'));
}
}
// View code - app/View/Posts/json/index.ctp
foreach ($posts as &$post) {
unset($post['Post']['generated_html']);
}
echo json_encode(compact('posts', 'comments'));
// Controller
public function listAll() {
$myModel = $this->MyModel->find('all');
if($this->request->is('ajax') {
$this->layout=null;
// What else?
echo json_encode($myModel);
exit;
// What else?
}
}
You must use exit after the echo and you are already using layout null so that is OK.
You do not have to use View for this, and it is your wish to work with components. Well all you can do from controller itself and there is nothing wrong with it!
Iinjoy
In Cakephp 3.5 you can send json response as below:
//in the controller
public function XYZ() {
$this->viewBuilder()->setlayout(null);
$this->autoRender = false;
$taskData = $this->_getTaskData();
$data = $this->XYZ->getAllEventsById( $taskData['tenderId']);
$this->response->type('json');
$this->response->body(json_encode($data));
return $this->response;
}
Try this:
public function listAll(){
$this->autoRender=false;
$output = $this->MyModel->find('all')->toArray();
$this->response = $this->response->withType('json');
$json = json_encode($output);
$this->response = $this->response->withStringBody($json);
}

codeigniter best way to create controller for editing a db row

Im new to codeigniter and im developing my first web application with it and want to make sure im doing best practices the 1st time so i dont have to go back to make corrections down the road. with that said, here is what im doing.
I want to edit a note in the DB, then after the record has been updated redirect to a different page.
my model is coded correctly so im not worried there, but the controller looks like this (and this is probably not correct:
public function edit($id) {
$this->load->model('Notes_model');
if (isset($_POST["edit"]))
{
$data['data'] = $this->Notes_model->edit($id);
$url = "/Notes/view/" . $id;
redirect($url);
}
$data['notes'] = $this->Notes_model->viewNotes($id);
$this->load->view('templates/header');
$this->load->view('notes/edit', $data);
$this->load->view('templates/footer');
}
hopefull this makes sense, basically what I'm wanting to do here is:
1.) Show the edit note page
2.) if i edited that page by hitting submit
a.) update the db
b.) redirect to a different page.
does this look pretty good or should i make some better changes?
Although your controller code is fine but one thing you have to take care that you should load model in the constructor of your controller so you don't have to include the model in each function same recommendations for the libraries, helpers this is the best practice
class myclass extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('Notes_model');
$this->load->helper(form);
}
public function myfunction(){
}
}
Here is the starting tutorial with MVC standards advanced-codeigniter-techniques-and-tricks
<?php
class Home extends CI_Controller
{
function __construct() {
parent::__construct();
$this->m_auth->notLogin();
$this->load->library('form_validation');
$this->load->library('ajax_pagination');
$this->load->library('dateconverter');
$this->load->helper('template');
$this->load->helper('check');
$this->load->model('mymodels/crud_model');
$this->lang->load('personal', $this->m_auth->get_language());
$this->lang->load('global', $this->m_auth->get_language());
}
function index()
{
$this->get_recs();
}
function get_recs()
{
//get for view or first page to be showed
}
/**
* Register New User
*/
function updateRecords()
{
$this->form_validation->set_rules('ministery','<span class="req">(Ministry)</span>','trim|required');
$this->form_validation->set_rules('directorate','<span class="req">(Directorate)</span>','trim|required');
if($this->form_validation->run()==FALSE)
{
header_tpl($this->m_auth->get_language(),'a');
banner_tpl($this->m_auth->get_language(),'a');
left_tpl($this->m_auth->get_language(),'a');
$content = $this->load->view('personal/edit_personal', $this->POST,true);
content_tpl($content);
footer_tpl();
}
else
{
$form_data = array(
'ministry' => $this->input->post('ministery'),
'directorate' => $this->input->post('directorate'),
'job_province' => $this->input->post('job_province'),
'job_district' => $this->input->post('job_district'),
'first_name' => $this->input->post('fname'),
'last_name' => $this->input->post('lname')
);
if($this->crud_model->update_recs('ast_emp_property',$form_data)==TRUE)
{
$this->session->set_flashdata("msg","<span class='m_success'>".$this->lang->line('global_insert_success')."</span>");
redirect('/home/success_reg/'.$id.'','refresh');
}
else
{
$this->session->set_flashdata("msg","<span class='m_error'>".$this->lang->line('global_insert_error')."</span>");
redirect('home','refresh');
}
}
}
}
?>

Rolling-curl Codeigniter library

I've been using this rolling-curl library with success outside of Codeigniter http://code.google.com/p/rolling-curl/source/browse/#svn%2Ftrunk
I want to use the library with Codeigniter but cannot get it to work.
I've created a file called Rollingcurl.php and placed in codeigniter's application/library folder. In this file I've copied the originals RollingCurl.php file's content (see RollingCurl.php file in link posted above).
My controller looks like this:
class Rolling_curl extends CI_Controller {
function __construct()
{
parent::__construct();
}
function index(){
$this->load->library('rollingcurl', 'request_callback');
$this->rollingcurl->request("http://www.google.com");
$this->rollingcurl->execute();
}
function request_callback($response, $info, $request) {
// parse the page title out of the returned HTML
if (preg_match("~<title>(.*?)</title>~i", $response, $out)) {
$title = $out[1];
}
echo "<b>$title</b><br />";
print_r($info);
print_r($request);
echo "<hr>";
}
In the index function I'm loading the rollingcurl library I've created from the orginal RollingCurl.php and passing the parameter 'request_callback', which is the name of the other function in the controller (see orginal rolling-curl example: http://code.google.com/p/rolling-curl/source/browse/trunk/example.php).
But, it doesn't work... What am I doing wrong?

Resources