Laravel 5.1 Download PDF with Event - php

My initial controller code for Event is:
try {
$sales = $this->sales->create([
'customer_id' => $customer->id,
'sales_details' => json_encode($vData),
'total_price' => ((int)$data['q-rfh'] * (int)$data['p-rfh']) + ((int)$data['q-rfh-spro'] * (int)$data['p-rfh-spro']),
'created_by' => $user->username,
]);
\Event::fire('print.invoice', $sales);
return \Response::json([
'type' => 'success',
'message' => 'Success creating sales!',
]);
}
catch (\Exception $e) {
return \Response::json([
'type' => 'danger',
'message' => $e->getMessage(),
]);
}
I need to print the invoice using event because I need to return a response with ajax to let user know the sales has been successfully made.
The event code is as simple as this:
public function handle(SalesModel $sales) {
if ($sales) {
$data = [
'sales' => $sales,
];
$pdf = \PDF::loadView('invoice.sales', $data);
return $pdf->download('inv_' . Carbon::now() . '.pdf');
}
}
EventServiceProvider already listens to it:
protected $listen = [
'print.invoice' => [
'App\Events\InvoiceEventHandler',
],
];
Everything works fine, except that the PDF is not downloaded. I'm using https://github.com/barryvdh/laravel-dompdf for creating and downloading the PDF. Can someone tell me what's wrong?

I give you and idea. Create the pdf file and store it at your server temporally
// return an absolute url
$pdfFile = \PDF::create('inv_' . Carbon::now() . '.pdf');
Now in your json response add the pdf file url in order to download it once the response arrives at client:
return \Response::json([
'type' => 'success',
'message' => 'Success creating sales!',
'pdf' => pdfFile
]);
From javascript, at success() method you can call the pdf in other request

Related

Is there a way to test Laravel's email configuration to check if it connects with the server?

I am building a CMS-like installer for my laravel project. I have updated the laravel.env file.
Now, I want to test the email configuration, I end up getting this error:
This is my controller code:
public function processEmailConfig(){
// // Create tables
// Artisan::call('migrate:fresh', ['--force' => true]);
// // Run seeder
// Artisan::call('db:seed', ['--force' => true]);
$data = Validator::make(request()->all(), [
'mail_host' => 'required',
'mail_port' => 'required|numeric',
'mail_username' => 'required',
'mail_password' => 'required',
'mail_encryption' => 'required',
'mail_from' => 'required',
]);
if($data->fails()){
return response()->json(['errors'=>$data->errors()->all()]);
}
$data = $data->validated();
$this::updateEnv('MAIL_HOST', $data['mail_host']);
$this::updateEnv('MAIL_PORT', $data['mail_port']);
$this::updateEnv('MAIL_USERNAME', $data['mail_username']);
$this::updateEnv('MAIL_PASSWORD', $data['mail_password']);
$this::updateEnv('MAIL_ENCRYPTION', $data['mail_encryption']);
$this::updateEnv('MAIL_FROM_ADDRESS', $data['mail_from']);
try {
Mail::to('info#chibuezevince.me')->send(new WelcomeEmail);
} catch (Exception $e) {
return response()->json(['errors'=>['Incorrect Email Configuration']]);
}
return response()->json(['success'=>['Success']]);
}
Please, how do I go about it?
I tried:
try {
Mail::to('info#chibuezevince.me')->send(new WelcomeEmail);
} catch (Exception $e) {
return response()->json(['errors'=>['Incorrect Email Configuration']]);
}
But as you can see, it still gives the same error.

response error REST API CI3 not display in Client

I'm having a problem getting errors from the Rest API I created with codeigniter 3, or rather using the library from "https://github.com/chriskacerguis/codeigniter-restserver".
This problem occurs when I POST data to server via API.
When I try to post the same data as the data in the database. it will issue an error message data already exists. with status 409.
but I didn't get the error in the client application that I made. only displays "Null"
https://localhost/server/api/room
public function index_post()
{
try {
$input = json_decode(file_get_contents('php://input'), true);
if (empty($input['noroom'])) {
throw new Exception('Error: field not found, field must be named noroom');
return false;
}
$exists = $this->Roommodel->findRoomByNoroomAndHotel($input['noroom'], $input['hotel_code'])->num_rows();
if ($exists > 0) {
$message = [
'status' => 409,
'message' => 'Data already exists',
];
$this->response($message, REST_Controller::HTTP_CONFLICT);
} else {
$dataRoom = [
'hotel_code' => $input['hotel_code'],
'noroom' => $input['noroom'],
'room_type' => $input['room_type'],
'room_area' => $input['room_area'],
'description' => $input['description'],
];
$insert = $this->Roommodel->save($dataRoom);
if ($insert) {
$data = [
'hotel_code' => $input['hotel_code'],
'noroom' => $input['noroom'],
'room_type' => $input['room_type'],
'room_area' => $input['room_area'],
'description' => $input['description'],
'message' => 'Success created data'
];
$message = [
'status' => 200,
'message' => 'Success',
'data' => $data,
];
$this->response($message, REST_Controller::HTTP_OK);
} else {
$message = [
'status' => 400,
'message' => 'Bad Request'
];
$this->response($message, REST_Controller::HTTP_BAD_REQUEST);
}
}
} catch (Exception $e) {
$message = [
'status' => 500,
'message' => $e->getMessage()
];
$this->response($message, REST_Controller::HTTP_INTERNAL_SERVER_ERROR);
}
}
below is my coding on the client side, and I try to do var_dum() the result is "Null" when there is an error.
when I tried insomia, I got the error message.
var $API = "";
function __construct()
{
parent::__construct();
$this->API = "http://localhost/server";
$this->load->library('session');
$this->load->library('curl');
$this->load->helper('form');
$this->load->helper('url');
}
public function create()
{
if ($this->input->is_ajax_request()) {
$data = [
'hotel_code' => $this->input->post('hotel_code'),
'noroom' => $this->input->post('noroom'),
'room_type' => $this->input->post('room_type'),
'room_area' => $this->input->post('room_area'),
'description' => $this->input->post('description'),
];
$response = json_decode($this->curl->simple_post($this->API . '/api/room', json_encode($data), array(CURLOPT_BUFFERSIZE => 10)), true);
var_dump($response); die();
echo json_encode($response);
} else {
show_404();
}
}
if the post data is successful, it will send the success message. and managed to get the message.
please help me to solve this problem

Illuminate\Validation\Factory::make(): Argument #1 ($data) must be of type array, App\Models\Product given

This is my controller function to store a product, i have the error in the $validator, i'm using this in the api route, i have the error of the title, i've try so many things and nothing works, please helpme, if i send in $validator the $req->all() it works, but i need to send a picture and thats why i'm using the $productReq, i'm using laravel 8
public function store(Request $req)
{
$productReq = new Product($req->all());
if ($req->file('file') == null) {
$req->file = "";
} else {
$image = $req->file('file')->store('public/images');
$url = Storage::url($image);
$productReq->file = $url;
}
$rules = array(
'name' => 'required',
'price' => 'required',
'file' => 'required|image'
);
$validator = Validator::make($productReq, $rules);
if ($validator->fails()) {
return response()->json([
'error' => true,
'response' => $validator->errors()
], 401);
} else {
$product = Product::create($productReq);
return response()->json([
'error' => false,
'response' => $product,
], 200);
}
}
Validator::make() expects an array of data to be provided to it. You've provided an instance of a Product, which Laravel doesn't know what to do with. What you want to do is validate your data before creating an instance of Product.
public function store(Request $req)
{
$rules = array(
'name' => 'required',
'price' => 'required',
'file' => 'required|image'
);
$validator = Validator::make($req->input(), $rules);
if ($validator->fails()) {
return response()->json([
'error' => true,
'response' => $validator->errors()
], 401);
}
$product = new Product($req->input());
if ($req->file('file') == null) {
$req->file = "";
} else {
$image = $req->file('file')->store('public/images');
$url = Storage::url($image);
$product->file = $url;
}
$product->save();
return response()->json([
'error' => false,
'response' => $product,
], 200);
}
You can also simplify the controller's logic by making use of some of Laravel's conveniences. However, it may produce responses that do not match what the front end expects (i.e. JSON message when a validation error is encountered).
public function store(Request $req)
{
// Laravel's `validate()` method on a Request will validate against the
// current request data and return the valid input. It will throw an Exception
// if validation fails, which Laravel will handle and reply with the validation errors.
$validatedInput = $req->validate([
'name' => 'required',
'price' => 'required',
'file' => 'required|image'
])
$product = new Product($validatedInput);
// ... file logic
$product->save();
// In Laravel, you can return an array from a controller. Laravel
// will assume it's supposed to be JSON, and encode it automatically for you
return [
'error' => false,
'response' => $product,
];
}

Unable to obtain instance of HTTP request in Laravel 5.8

I am having trouble retrieving form values using the Illuminate\Http\Request class.
I have an endpoint that creates a product and another that updates it set up like this
Route::post('products', 'ProductController#store');
Route::put('products/{product}', 'ProductController#update');
The store and update methods in the ProductController are
public function store(Request $request)
{
// validate inputs
$validator = Validator::make($request->all(), [
'name' => 'required',
'category' => 'required',
'status' => 'required',
'price' => 'required',
'image' => 'required|image|mimes:jpeg',
'interest' => 'required'
]);
// return 401 response if validation fails
if ($validator->fails()) {
return response()->json([$validator->errors()], 401);
}
// create & store the product
if ($product = Product::create([
'name' => $request->name,
'category' => $request->category,
'status' => $request->status,
'price' => $request->price,
'interest' => $request->interest,
])) {
// store the product image
$file = $request->file('image');
$destinationPath = "public/images/products";
$filename = 'pramopro_' . $product->name . '_' . $product->id . '.' . $file->extension();
Storage::putFileAs($destinationPath, $file, $filename);
ProductImage::create([
'product_id' => $product->id,
'name' => $filename
]);
}
// return new product
return new ProductResource($product);
}
public function update(Request $request, Product $product)
{
// dd($request);
// validate inputs
$validator = Validator::make($request->all(), [
'name' => 'required',
'category' => 'required',
'status' => 'required',
'price' => 'required',
'image' => 'required|image|mimes:jpeg',
'interest' => 'required'
]);
// return 401 response if validation fails
if ($validator->fails()) {
return response()->json([$validator->errors()], 401);
}
// update this product
if ($product) {
$product->update($request->all());
return new ProductResource($product);
} else {
return response()->json(["error" => "Not found"], 404);
}
}
Now when I test the endpoints in postman, I can successfully create a new product record. But if I try to update a product, I get a 401 unauthorized error even though all the required fields are filled. dd($request)returns null but dd($product) returns the product as expected.
Maybe I have been looking at it so hard so I have missed something. What am I doing wrong?
This is the reasons I think why the $request return null
The store and update request is same name. Two input name or select name or textarea name can't be the same name in the same web page. If its same it will always get the first one that is the reason why it is returning null because the first one is empty.
The name you're calling is incorrect
Hope it helps!

How can I assign 'g-recaptcha-response' to a variable? With 'g-recaptcha-response' being a parameter inside $request->validate([])

So what i want is to put 'g-recaptcha-response' in a variable to be able to use it in my condition to verify recaptcha but I haven't been able to do this. Is there any way to only use recaptcha field from the array inside validate() because my code as it is, redirects me back to homepage. It goes straight to else statement.
public function contactanospost(Request $request){
$request->validate([
'nombre' => 'required|distinct',
'telefono'=> 'required|telefono',
'correo' => 'required|email',
'mensaje' => 'required',
'g-recaptcha-response' => 'required|captcha',
]);
if(POST['g-recaptcha-response']){ /*here I am trying to
check with a condition if recaptch was really validated once the form is submitted */
$token= POST['g-recaptcha-response'];
$client = new Client();
$response = $client->post('https://www.google.com/recaptcha/api/siteverify', [
'form_params' => array('secret' => 'mycaptchakey',
'response'=> $token /*Checking with google parameters for recaptcha if the user was indeed verified */
)
]);
$resultados = json_decode($response->getBody()->getContents()); //decode with json
if($resultados->success){ /*if this was a success then return a page with parameters from google recaptcha such as: secret, response, remote ip.*/
dd($resultados); /*show the results from verified user and that recaptcha is working*/
$contactanos = Contactanos::create($request->all());/* and create all fields for model Contactanos*/
Mail::to('some#mail')->send(new enviacorreo($contactanos)); /* since it is a contact form then send all the information to some mail*/
\Session::flash('flash_message','Tu mensaje ha sido enviado!'); /* send a message with "email delivered" verification*/
return redirect()->back();
}
else{
\Session::flash('flash_message','Robot');
return redirect('/');
}
}
else{
return redirect('/');
}
}
I'm now able to access request properties using input() what got me confused were my if statements. The real problem is that after:
$resultados = json_decode($response->getBody()->getContents());
next if statement is not getting the expected success but instead it goes straight to else with robot message:
else{
\Session::flash('flash_message','Robot');
return redirect('/');
}
You can access all the properties of the request from the $request object by calling e.g, $request->input('g-recaptcha-response') This is the basic of Accessing the request if you have read through the documentation.
I can lend you a snippet to do this perhaps it will help you rethink how you're validating the captcha:
use GuzzleHttp\Client;
....
$v = Validator::make($request->all(), [
'name' => 'required|min:2',
'email' => 'required|email|max:255',
'subject' => 'sometimes|required|min:3',
'message' => 'required|min:3',
'g-recaptcha-response' => 'sometimes|required'
], [
'g-recaptcha-response.*' => 'Please verify that you are not a robot'
]);
if ($v->fails()) {
return [
'success' => 'no',
'data' => $v->errors()->first()
];
}
if ($request->get('g-recaptcha-response')) {
$verify_form = [
'secret' => env('GOOGLE_RECAPTCHA_SECRET', 'default'), //better to save in config though
'response' => $request->get('g-recaptcha-response')
];
$client = new Client();
$verify_serial = '?'.http_build_query($verify_form);
$response = $client->post('https://www.google.com/recaptcha/api/siteverify'.$verify_serial);
$arrayed_response = json_decode($response->getBody()->getContents(), true);
if(!$arrayed_response['success']){
Log::notice('There is something wrong with the verification of recaptcha: ',$arrayed_response );
return [
'success' => 'no',
'data' => 'Something went wrong in verification process',
];
}
}
The idea is that, you build the secret and response body and use that to request validation check from Google just as you have done but building the query as query parameters directly to the url.
PS: you don't have to return the snippet :)

Categories