How to insert into couchDB in laravel - laravel

How to insert the records to couchDB in laravel. i have done the retrieval part but now I want to do insert, update and delete .
My retrieval code is below.
class couchdbcontroller extends Controller
{
public function getdata()
{
$content =null;
try {
$client = new Client();
$apiRequest = $client->request('GET','http://localhost:5984/user/_design/userdesign/_view/user-view?limit=20&reduce=false');
$code = $apiRequest->getBody()->getContents();
} catch (RequestException $re) {
//For handling exception
return $re->error;
}
return $code;
//return response()->json($code);
}
}
Inserting code below:
public function guzzle_insert_doc()
{
$client = new Client();
$res = $client->request('PUT', 'http://localhost:5984/login/new_doc',[
'uname' => 'admin',
'password' => 'admin123',
]);
//return $res;
}
Error: Client error: PUT http://localhost:5984/login/new_doc resulted in a 400 Bad Request response:
{"error":"bad_request","reason":"invalid UTF-8 JSON"}

From my google search, you could do something like this :
<?php
$client = new Client();
$doc = ['title'=>'This is a new doc'];
$res = $client->request('PUT', 'http://localhost:5984/db/new_doc',['json' => $doc]);
I assume you're using Guzzle (If I am wrong, tell us what your are using)
I didn't test my code since I don't have time to setup a laravel project with Guzzle. See documentation for further help.

Related

How with jenssegers/mongodb get last Insert Id?

On Laravel site using jenssegers/mongodb I have store method like :
public function store(ItemRequest $request)
{
$request = request();
try {
$session = DB::getMongoClient()->startSession();
$session->startTransaction();
$insertData = $request->all();
$insertData['published'] = ! empty($insertData['published']);
$item = Item::create([
'title' => $insertData['title'],
'text' => $insertData['text'],
'published' => $insertData['published'],
]);
$session->commitTransaction();
} catch (Exception $e) {
$session->abortTransaction();
return back()->withErrors(['message' => $e->getMessage()]);
}
return redirect(route('admin.items.edit', $item->_id))
->with('message', 'New item was successfully added')
->with('message_type', 'success');
}
But making test for this controller method I did not find how to get ID on new ite, generated on mongodb site :
public function testIsItemEditFormSubmittedWithSuccess()
{
$this->withoutMiddleware();
$item = \App\Models\Item::factory(Item::class)->make();
// Test Action
$response = $this->actingAs(self::$loggedAdmin, 'web')->post(route('admin.items.store'), $item->toArray());
$newItemId = DB::getPdo()->lastInsertId();
// If to uncomment line above I got "Error: Call to a member function lastInsertId() on null"
$response->assertStatus(302); // Redirection status
$response->assertRedirect(route('admin.items.edit', [???])); // HOW can New ID on "store" method above ?
$response->assertSessionHasNoErrors();
}
Any equvalent of lastInsertId for jenssegers/mongodb ?
"jenssegers/mongodb": "^3.9.2",
"laravel/framework": "^9.30.1",
Thanks in advance!
Check this issue.
https://github.com/jenssegers/laravel-mongodb/issues/2451
Your laravel should be 9.31. So downgrade it to 9.30 and wait next release.

Laravel - Using Stream with the new Http client

I'm migrating my old system to the new version of Laravel, and I'm having problems with one of my requests...
Basically on this request I receive any file and simply forward it to the user. Here is the old version using Guzzle:
use Symfony\Component\HttpFoundation\StreamedResponse;
public function getMedia($media)
{
try {
$response = $this->client->get('media/' . $media, [
'stream' => true
]
);
$contentType = $response->getHeader('Content-Type');
$body = $response->getBody();
$stream = new StreamedResponse(function () use ($body) {
while (!$body->eof()) {
echo $body->read(1024);
}
});
$stream->headers->set('Content-Type', $contentType);
return $stream;
} catch (ClientException $e) {
return response()->json([
'errors' => json_decode($e->getResponse()->getBody()->getContents())->errors,
'message' => 'Unfortunately we could not find the requested file'
], 404);
}
}
And the new code that I tried to write, without success:
use Symfony\Component\HttpFoundation\StreamedResponse;
public function getMedia($media)
{
$response = Http::withOptions([
'stream' => true
])->get("media/{$media}");
$contentType = $response->header('Content-Type');
$body = $response->body();
$stream = new StreamedResponse(function () use ($body) {
while (!$body->eof()) {
echo $body->read(1024);
}
});
$stream->headers->set('Content-Type', $contentType);
return $stream;
}
Does anyone have any idea how to solve this? I don't know what to do anymore...
I know, 2 years late, but i'm doing something similar, you should access to the response via the psr
instead of:
$body = $response->body(); // This try to return an string
Use this:
$body = $response->toPsrResponse()->getBody(); // the guzzle response
Then you can use your normal code
I hope someone can find this useful,

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');
}
}

extend larasap/fb post method

I'm trying to extend the functionality of a method from this package:
https://github.com/toolkito/laravel-social-auto-posting
Because the usage from mine controller is so simple, and others package makes a big mess even for basic operation like the one I need to achieve!
Goal: -posting text over a fb page with some tags of users that have allready puted a like to the same page.
So I Start from this call:
SendTo::Facebook(
‘link’,
[
‘link’ => ‘https://github.com/toolkito/laravel-social-auto-posting',
‘message’ => ‘Laravel social auto posting’
]
);
If I simply cut the link part, the message part can be my text of the post, and all works easy.
If I try to add user's tag on the 'message' part with the notation:
#[userId]
thats not works and the tag part is cutted and only the text is showed:
If I send 'text'=>'some text #[mineuserid] more text''
only
'some text more text'
is showed on the wall.
So I move to copy and extend the methods.
If I well understand from fb documentation I can tags user with the field tags but needs to be specified even the field places (in that case if I well understand my page's id)
So I start to explore into package, and trying to mods over sends link of the package:
public static function Facebook($type, $data)
{
switch ($type) {
case 'link':
$message = isset($data['message']) ? $data['message'] : '';
$result = FacebookApi::sendLink($data['link'], $data['message']);
break;
case 'postolo':
$message = isset($data['message']) ? $data['message'] :'';
$tags =isset($data['tags']) ? $data['tags'] : '';
$places =isset($data['places']) ? $data['places'] : '';
$result = FacebookApi::sendPostolo( $message, $tags,$places);
break;
Mine part is "postolo"
Then I found sendLink:
public static function sendLink($link, $message = '')
{
self::initialize();
$data = compact('link', 'message');
try {
$response = self::$fb->post('/me/feed', $data, self::$page_access_token);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
throw new \Exception('Graph returned an error: '.$e->getMessage());
} catch(Facebook\Exceptions\FacebookSDKException $e) {
throw new \Exception('Facebook SDK returned an error: '.$e->getMessage());
}
$graphNode = $response->getGraphNode();
return $graphNode['id'];
}
If I foolishly copy this and adapts it to my needs is something like:
public static function sendPostolo($link, $message = '',$tags='',$places='')
{
self::initialize();
$data = compact( 'tags','message','places');
try {
$response = self::$fb->post('/me/feed', $data, self::$page_access_token);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
throw new \Exception('Graph returned an error: '.$e->getMessage());
} catch(Facebook\Exceptions\FacebookSDKException $e) {
throw new \Exception('Facebook SDK returned an error: '.$e->getMessage());
}
$graphNode = $response->getGraphNode();
return $graphNode['id'];
}
But at the end the method $fb->post() not works as espect to me, and just publishs the first data of my array $data = compact( 'tags','message','places'); so in that case 'tags' and not as tags but predictably as plain text...
this is post() on fb package:
public function post($endpoint, array $params = [], $accessToken = null, $eTag = null, $graphVersion = null)
{
return $this->sendRequest(
'POST',
$endpoint,
$params,
$accessToken,
$eTag,
$graphVersion
);
}

Rollback not working in laravel multiple database in 5.2

Rollback not working in laravel multiple database in 5.2. What can i do? please help me. Advance thanks.
public function TestingRegistration(){
$now=date('Y-m-d H:i:s');
$faculty_user_account=array(
'user_id' =>'466297',
'name' => 'Hello',
);
\DB::beginTransaction();
try{
$save_registration=\DB::table('users')->insert($faculty_user_account);
$view2= \DB::connection('mysql_2')->table('users')->insert($faculty_user_account);
$view3 = \DB::connection('mysql_3')->table('users')->insert($faculty_user_account);
\DB::commit();
return \Redirect::back()->with('message',"Faculty Registration Successfull!");
}catch(\Exception $e){
\DB::rollback();
$message = "Message : ".$e->getMessage().", File : ".$e->getFile().", Line : ".$e->getLine();
return \Redirect::back()->with('errormessage',$message);
}
}
The easy way to do transaction is to use it as a callback, this way it will be handle it automatically for you.
public function TestingRegistration(){
$now = \Carbon::now(); // Where is this use?
$faculty_user_account = [
'user_id' => '466297',
'name' => 'Hello',
];
$success = \DB::transaction(function () use ($faculty_user_account) {
$save_registration = \DB::table('users')->insert($faculty_user_account);
$view2 = \DB::connection('mysql_2')->table('users')->insert($faculty_user_account);
$view3 = \DB::connection('mysql_3')->table('users')->insert($faculty_user_account);
return (bool) $view2 && $view3;
});
if (! $success) {
return \Redirect::back()->with('errormessage', 'Unable to save.');
}
return \Redirect::back()->with('message',"Faculty Registration Successfull!");
}
PS: I can't remember what insert returns, let me check later to make sure it can be use like that for testing success.

Resources