Laravel Create a request internally Resolved - laravel

I need to recreate a resquest so that it behaves like a call via api to go through the validator, but my $request->input('rps.number') always arrives empty, although I can see the data in the debug
I also couldn't get it to go through the laravel validator
I can't use a technique to make an http call, because I need to put this call in a transaction
<?php
$nota = new stdClass();
$rps = new stdClass();
$rps->numero = (int)$xml->Rps->IdentificacaoRps->Numero;
$rps->serie = (string)$xml->Rps->IdentificacaoRps->Serie;
$rps->tipo = (int)$xml->Rps->IdentificacaoRps->Tipo;
$nota->rps = $rps;
$controller = new NotaController(new Nota());
$content = new StoreNotaRequest();
$content->request->add($nota);
$result = $controller->store($content);
StoreNotaRequest
<?php
class StoreNotaRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
$request = $this->request;
return [
'rps.numero' => 'required_with:rps|numeric|between:1,999999999999999',
'rps.serie' => 'required_with:rps|string|min:1|max:5',
'rps.tipo' => 'required_with:rps|integer|in:1,2,3'
];
}
}
NotaController
<?php
class NotaController extends Controller
{
private Nota $nota;
public function __construct(Nota $nota)
{
$this->nota = $nota;
}
public function store(StoreNotaRequest $request): JsonResponse
{
// $validated = $request->validated();
try {
$nota = DB::transaction(function () use ($request) {
$request->input('rps.numero');
});
return response()->json($nota);
} catch (Throwable $e) {
return response()->json($data, 409);
}
}
}
Solution
the solution was a little too verbose, I believe it is possible to solve with less code.
more does what it needs to go through the validation of the data contained in the StoreNotaRequest
and it returns an http response, in addition to being able to put all these isolated calls in a single transaction
DB::beginTransaction();
$errors = [];
foreach ($itens as $item) {
$controller = new NotaController(new Nota());
$request = new StoreNotaRequest();
$request->setMethod('POST');
$request->request->add($nota);
$request
->setContainer(app())
->setRedirector(app(Redirector::class))
->validateResolved();
$response = $controller->store($request);
if ($response->statusText() !== 'OK') {
$errors[$item->id] = 'ERROR';
}
}
if (count($errors) === 0) {
DB::commit();
} else {
DB::rollBack();
}

Related

Post with xml file in laravel

I am using method post to create new data in xml file but The function c_element cannot be used in the function store
$DeTai = c_element('DeTai', $root);
This is my current code:
public function c_element($e_name, $parent)
{
global $xml;
$node = $xml->createElement($e_name);
$parent->appendChild($node);
return $node;
}
public function c_value($value, $parent)
{
global $xml;
$value = $xml->createTextNode($value);
$parent->appendChild($value);
return $value;
}
public function store(Request $request)
{
$xml = new DOMDocument("1.0","UTF-8");
$xml->load('../xml/QuanLyDoAnTotNghiep.xml');
if ($request->isMethod('post'))
{
$madt= $request->madt;
$noidungdetai = $request->noidungdetai;
$root=$xml->getElementsByTagName("QuanLyDoAnTotNghiep")->item(0);
$DeTai = c_element("DeTai", $root); //error in here
$s_madt = c_element('MaDT', $DeTai);
c_value("$madt", $s_madt);
$s_noidungdetai = c_element('NoiDungDeTai', $DeTai);
c_value("$noidungdetai", $s_noidungdetai);
$xml->formatOutput=true;
$xml->save('../xml/QuanLyDoAnTotNghiep.xml');
echo "Thêm mới thành công!!!";
}
}
use this keyword to call one method in different method of same class
$DeTai = $this->c_element('DeTai', $root);
to know more about it please visit this
Thanks..

How to compare otp number without reload page which send in sms?

I want to compare otp numbers, which i type in textbox and sms otp sent to the number through api calling controller in laravel.
i use laravel5.6 and php 7.2.3
public function otpverify(Request $req)
{
$otpenter=$req->txtotp;
if ($otpenter==$otp)
{
return redirect()->action('JaincountController#create')
}
else
{
return view('jaincount_user/verification');
}
}
public function makeRequest(Request $req)
{
$client = new Client();
$otp=rand(10000,4);
// $data=
$data = array('adhar'=>$req->txtadharnumber,'drp'=>$req->drpcode,'mobilenumber'=>$req->txtnumber);
$response = $client->request('POST','http://192.168.1.9/jaincountapi/public/api/otpsms',[
'form_params'=>[
'adharcardnumber'=>$req->txtadharnumber,
'mobilecode'=>$req->drpcode,
'mobilenumber'=>$req->txtnumber,
'otp'=>$otp
]
]);
$response = $response->getBody();
return json_decode($response,true);
}
i want to compare textbox otp number and sms otp number sent through api calling and redirect with another controller in laravel5.6
The thing is you must store your otp in database or in session variable.
(Documentation: https://laravel.com/docs/5.8/eloquent)
You can store otp in database like
public function makeRequest(Request $req)
{
$client = new Client();
$otp=rand(10000,4);
// $data=
$data = array('adhar'=>$req->txtadharnumber,'drp'=>$req->drpcode,'mobilenumber'=>$req->txtnumber);
//CHANGES
User::where('phone_number',$req->txtnumber)->update(['otp'=>$otp]);
$response = $client->request('POST','http://192.168.1.9/jaincountapi/public/api/otpsms',[
'form_params'=>[
'adharcardnumber'=>$req->txtadharnumber,
'mobilecode'=>$req->drpcode,
'mobilenumber'=>$req->txtnumber,
'otp'=>$otp
]
]);
$response = $response->getBody();
return json_decode($response,true);
}
you can retrieve it using eloquent in Laravel using
public function otpverify(Request $req)
{
$otpenter=$req->txtotp;
//CHANGES
$otp = User::where('phone_number', $phone_number)->first()->otp;
if ($otpenter==$otp)
{
return redirect()->action('JaincountController#create')
}
else
{
return view('jaincount_user/verification');
}
}
after entering the correct otp clear that in database.
Or you can use session.you can use session in two ways
1.php default session
2.Laravel Session
let us see php default session
(documentation:https://www.php.net/manual/en/book.session.php)
public function makeRequest(Request $req)
{
$client = new Client();
$otp=rand(10000,4);
// $data=
$data = array('adhar'=>$req->txtadharnumber,'drp'=>$req->drpcode,'mobilenumber'=>$req->txtnumber);
//CHANGES
session_start();
$_SESSION['otp'] = $otp
$response = $client->request('POST','http://192.168.1.9/jaincountapi/public/api/otpsms',[
'form_params'=>[
'adharcardnumber'=>$req->txtadharnumber,
'mobilecode'=>$req->drpcode,
'mobilenumber'=>$req->txtnumber,
'otp'=>$otp
]
]);
$response = $response->getBody();
return json_decode($response,true);
}
you can retrieve it by
public function otpverify(Request $req)
{
$otpenter=$req->txtotp;
//CHANGES
session_start();
$otp = $_SESSION['otp']
if ($otpenter==$otp)
{
return redirect()->action('JaincountController#create')
}
else
{
return view('jaincount_user/verification');
}
}
let us use laravel session
(documentation: https://laravel.com/docs/5.2/session)
//important
use Illuminate\Support\Facades\Session;
public function makeRequest(Request $req)
{
$client = new Client();
$otp=rand(10000,4);
// $data=
$data = array('adhar'=>$req->txtadharnumber,'drp'=>$req->drpcode,'mobilenumber'=>$req->txtnumber);
//CHANGES
Session::put('otp',$otp)
$response = $client->request('POST','http://192.168.1.9/jaincountapi/public/api/otpsms',[
'form_params'=>[
'adharcardnumber'=>$req->txtadharnumber,
'mobilecode'=>$req->drpcode,
'mobilenumber'=>$req->txtnumber,
'otp'=>$otp
]
]);
$response = $response->getBody();
return json_decode($response,true);
}
you can retrieve it by
//important
use Illuminate\Support\Facades\Session;
public function otpverify(Request $req)
{
$otpenter=$req->txtotp;
//CHANGES
$otp = Session::get('otp') //best way to use is flash. see the full documentation
if ($otpenter==$otp)
{
return redirect()->action('JaincountController#create')
}
else
{
return view('jaincount_user/verification');
}
}

Undefined property: GuzzleHttp\Exception\ConnectException::$status

I keep getting this error when trying to get the status of the request.
This is my code
ExpenseRepository.php
<?php
namespace Expensetrim\Api\v1\Repositories;
use Auth;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Expensetrim\Models\Company;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class ExpenseRepository
{
private $api_url;
const API_GET = 'GET';
const API_POST = 'POST';
const API_PUT = 'PUT';
function __construct()
{
$this->api_url = "http://xxx-xxx-xxx/api/v1/";
}
public function api_call($method, $uri, $request = NULL)
{
try {
$url=$this->api_url.$uri;
$client = new Client(['base_uri' => $this->api_url]);
$response = ($request) ? $client->request($method, $uri, $request) : $client->request($method, $uri);
}
catch (RequestException $e) {
return $e;
}
return $this->formatResponseBody($response);
}
public static function formatResponseBody($response)
{
$body = $response->getBody(true)->getContents();
return json_decode($body);
}
public function addExpenseType($data)
{
$uri = 'expense/types/add';
$response = $this->api_call(self::API_POST, $uri, ['form_params' => $data]);
return $response;
}
Also CompanyRepository.php
public function addExpenseType($company_id, $data)
{
$data['company_id'] = $company_id;
$expense = new ExpenseRepository;
$done = $expense->addExpenseType($data);
if($done->status == 'success') {
return true;
}
return true;
}
I need to check if the status is a success or not but keep getting this error: Undefined property: GuzzleHttp\Exception\ConnectException::$status.
Please what am i doing wrong?
There is an exception thrown at this line:
catch (RequestException $e) {
return $e;
}
and you are returning the exception. The return value of the method addExpenseType is actually an exception thrown by Guzzle.
throw the exception to see the error.
change your code to
catch (RequestException $e) {
throw $e;
}
Change your formatResponseBody function to add $response->getBody()->rewind();
public static function formatResponseBody($response)
{
$response->getBody()->rewind();
$body = $response->getBody(true)->getContents();
return json_decode($body);
}
In the old version of guzzle, it read the full body without resetting the pointer after. Using rewind() will reset the pointer. If this is the source of your issue rewind() will resolve this. It has aleady been resolved in newer versions.

Make an Ajax request in Symfony2

My problem is that the method doesn't return a true result.
I want to test if the email of input exists in my entity or not.
Here is the controller:
public function verificationAction(Request $request)
{
if ($this->container->get('request')->isXmlHttpRequest()) {
$email=$request->request->get('email');
$em=$this->getDoctrine()->getEntityManager();
$resp= $em->getRepository("CMSiteBundle:Prospect")->findBy(array('email'=>$email));
$response =new Response(json_encode($resp));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}
You could try an old-trick. Since in Symfony Controller Actions, You must return a Response why not fake a DEAD RESPONSE like so:
<?php
class ABCController {
public function verificationAction(Request $request) {
if ($this->container->get('request')->isXmlHttpRequest()) {
$email = $request->request->get('email');
$em = $this->getDoctrine()->getEntityManager();
$resp = $em->getRepository("CMSiteBundle:Prospect")
->findBy(array('email' => $email));
//$response = new Response(json_encode($resp));
//$response->headers->set('Content-Type', 'application/json');
// THE TRICK IS THAT DIE RUNS FIRST
// THUS SENDS YOUR RESPONSE YOU THEREBY
// STOPPING THE RETURN FROM FIRING... ;-)
return die(json_encode($resp));
}
}
}
Perhaps this very Old Trick still works for you... ;-)

How to cache model attributes in Laravel

In my current configuration, a user's email is stored on a remote server that I need to hit with a curl quest.
Luckily, I only need the email once a day when a certain process runs. However, when that process does run it will need to reference the email multiple times.
This is the current accessor I have set up for email. The problem is the curl request is being called every time I use $user->email. What's the best way to avoid this?
in UserModel:
public function getEmailAttribute(){
$curl = new Curl;
$responseJson = $curl->post('https://www.dailycred.com/admin/api/user.json',array(
'client_id'=>getenv('dailycredId')
,'client_secret'=>getenv('dailycredSecret')
,'user_id'=>$this->id
));
$response = json_decode($responseJson);
return $response->email;
}
private $cached_email = false;
public function getEmailAttribute(){
if ($this->cached_email){
// if set return cached value
return $this->cached_email;
}
// get the email
$curl = new Curl;
$responseJson = $curl->post('https://www.dailycred.com/admin/api/user.json',array(
'client_id'=>getenv('dailycredId')
,'client_secret'=>getenv('dailycredSecret')
,'user_id'=>$this->id
));
$response = json_decode($responseJson);
// cache the value
$this->cached_email = $response->email;
// and return
return $this->cached_email;
}
Depending on your use case make adjustments (ie. session, cache , static property...).
Extend a the Eloquent Model class
namespace App\Models\Utils;
use Illuminate\Database\Eloquent\Model as OldModel;
class MyModel extends OldModel
{
private $cachedAttributes = [];
public function getCachedAttribute(string $key, Callable $callable)
{
if (!array_key_exists($key, $this->cachedAttributes)) {
$this->setCachedAttribute($key, call_user_func($callable));
}
return $this->cachedAttributes[$key];
}
public function setCachedAttribute(string $key, $value)
{
return $this->cachedAttributes[$key] = $value;
}
public function refresh()
{
unset($this->cachedAttributes);
return parent::refresh();
}
}
make your class
class ElementWithEmail extends MyModel
{
const ATTRIBUTE_KEY_FOR_EMAIL = 'Email';
public function getEmailAttribute(){
$key = self::ATTRIBUTE_KEY_FOR_EMAIL;
$callable = [$this, 'getEmail'];
return $this->getCachedAttribute($key, $callable);
}
protected function getEmail()
{
$curl = new Curl;
$responseJson = $curl->post('https://www.dailycred.com/admin/api/user.json',array(
'client_id'=>getenv('dailycredId')
,'client_secret'=>getenv('dailycredSecret')
,'user_id'=>$this->id
));
$response = json_decode($responseJson);
return $response->email;
}
}
Call it from your code
$element = new ElementWithEmail();
echo $element->email;

Resources