I am trying to send post request with query params. just like this screenshot
I used Http::post but it supports only json as far as I know. I just want to send request just like the screenshot. cause API data only supports parameter wise. Here What I tried but failed to achieve that.
FormController.php:
public function post_parameter_wise(Request $request,$lp_campaign_id, $lp_campaign_key, $first_name, $last_name, $email, $phone, $zip_code){
$form = new Form();
$fName = $form->first_name = $request->get($first_name);
$lName = $form->last_name = $request->get($last_name);
$cCmail = $form->email = $request->get($email);
$cPhone = $form->phone = $request->get($phone);
$zCode = $form->zip_code = $request->get($zip_code);
$response = Http::post("https://t.vivint.com/post.do", [
"lp_campaign_id" => $lp_campaign_id,
"lp_campaign_key" => $lp_campaign_key,
// "lp_supplier_id" => "",
"first_name" => $fName,
"last_name" => $lName,
"email" => $cCmail,
"phone" => $cPhone,
"zip_code" => $zCode
]);
dd($response);
Can't leave a comment so disregard this as the answer
Preferably, you just need to change it from a Post request to a Get request and it will work
$response = Http::get("https://t.vivint.com/post.do", [...
But a post request will contain the data as a post request should.
If you have to use post and define the query params then you should do it as follows
public function post_parameter_wise(Request $request,$lp_campaign_id, $lp_campaign_key, $first_name, $last_name, $email, $phone, $zip_code){
$form = new Form();
$fName = $form->first_name = $request->get($first_name);
$lName = $form->last_name = $request->get($last_name);
$cCmail = $form->email = $request->get($email);
$cPhone = $form->phone = $request->get($phone);
$zCode = $form->zip_code = $request->get($zip_code);
$response = Http::post("https://t.vivint.com/post.do?lp_campaign_id=".$lp_campaign_id."&lp_campaign_key=".$lp_campaign_key."&first_name=".$fName."&last_name=".$lName."&email=".$cCmail."&phone=".$cPhone."&zip_code=".$zCode, []);
dd($response);
Although this is really just forcing it to
Related
I have a POST request with Guzzle like this:
// Return a collection
$cart = $this->getCart('2019-10-08 07:08:39');
//Return first entry of the collection with first()
$template = $this->getTemplate($config->key);
$isDetail = null;
foreach ($cart as $item) {
try {
$client = $this->getClient();
$headers = ['Content-Type' => 'application/json'];
$body = [
'user_id' => $item->mystore_user_id,
'title' => $template->title,
'message' => $template->message,
'avatar' => $template->avatar,
'detail_id' => $isDetail,
'schedule' => null
];
print_r($body);
$response = $client->post('push-noti/unicast', $headers, $body);
print_r(response()->json(json_decode($response->getBody(), true)));
} catch (QueryException | \Exception $ex) {
echo "Error!";
}
}
My body variable value is exist in each loop when it printed. But when I use it in $client->post, my request return error with user_id, title, message is required. I really don't know why is it?
Can you tell me what's wrong in my code?
Thank you!
Try
$response = $client->post('push-noti/unicast', ['body' => $body , 'headers' => $headers]);
If you are calling a third party API, replace push-noti/unicast with complete URL.
hello i have this function insertion works very well
function add_post(){
$this->form_validation->set_rules('user_id','User Id','trim|required');
//set msg if form validation false
if($this->form_validation->run() == FALSE){
$response = array('status' => FAIL, 'message' => strip_tags(validation_errors()));
$this->response($response);
}
$is_exist = $this->common_model->getsingle(USERS,array('userId'=>$this->post('user_id')));
if($is_exist){
$is_active = $this->common_model->getsingle(USER_COUPON,array('user_id'=>$is_exist->userId,'status'=>1));
$data['user_id'] = $is_exist->userId;
$data['user_coupon_id'] = $is_active->userCouponId;
$data['email'] = $is_exist->email;
$result = $this->common_model->insertData(USER_COUPON_SCAN,$data);
$response = array('status' => SUCCESS, 'message' => "success");
$this->response($response);
}
$response = array('status' => FAIL,'message' =>"No record found please try again");
$this->response($response);
}
the function recovers a single value user_id,I want to get a new value send by post (name admin_id) and isert in user_coupan_scan table
If you are sure that your code is working well, You can receive posted admin_id in following way.
function add_post(){
$this->form_validation->set_rules('user_id','User Id','trim|required');
//set msg if form validation false
if($this->form_validation->run() == FALSE){
$response = array('status' => FAIL, 'message' => strip_tags(validation_errors()));
$this->response($response);
}
$is_exist = $this->common_model->getsingle(USERS,array('userId'=>$this->post('user_id'))); // You may need to change $this->post('user_id') to $this->input->post('user_id')
if($is_exist){
$is_active = $this->common_model->getsingle(USER_COUPON,array('user_id'=>$is_exist->userId,'status'=>1));
$data['admin_id'] = $this->input->post('admin_id'); // make sure that the column name in your table is admin_id
$data['user_id'] = $is_exist->userId;
$data['user_coupon_id'] = $is_active->userCouponId;
$data['email'] = $is_exist->email;
$result = $this->common_model->insertData(USER_COUPON_SCAN,$data);
$response = array('status' => SUCCESS, 'message' => "success");
$this->response($response);
}
$response = array('status' => FAIL,'message' =>"No record found please try again");
$this->response($response);
}
In above answer, I have added one line i.e. receiving admin_id in post data.
$data['column_name_in_your_table'] = $this->input->post('name_in_post_data');
To receive data from post method you can do it like this
$some_name = $this->input-post('name');
Hope it helps.
I want to test my API controller that using some guzzle requests from another services.
I have one request for making a download link.
this is my API route
Route::group(['prefix' => '/v1'], function () {
Route::get('/exampledl', 'DownloadController#downloadChecker');
});
DownloadChecker controller checks if user is admin or subscriber makes a guzzle request to one of my services on a different domain, if not do another Guzzle request to another service and for each situations responses are different. This is a part of controller checks admin role.
$client = new Client();
try {
$response = $client->request('GET', 'https://www.example.com/api/user?u=' . $request->uid);
$json = \GuzzleHttp\json_decode($response->getBody()->getContents(), True);
// if user doesn't exist in CM
//this part has been written to avoid repeating code
if (array_key_exists('user', $json) && $json['user'] == null) {
abort(403);
}
elseif (in_array("administrator", $json['Roles'])) {
User::create([
'uid' => (int)$request->uid,
'subscription.role' => 'administrator',
]);
$client = new Client();
$response = $client->request('GET', "https://vod.example2.com/vod/2.0/videos/{$a_id}?secure_ip={$u_ip}", [
'headers' => [
'authorization' => '**********'
]
]);
$json = \GuzzleHttp\json_decode($response->getBody()->getContents(), TRUE);
if (isset($json['data']['mp4_videos'])) {
$links = [];
foreach ($json['data']['mp4_videos'] as $mp_video) {
if (stripos($mp_video, "h_144") !== false) {
$links['144p'] = $mp_video;
}
elseif (stripos($mp_video, "h_240") !== false) {
$links['240p'] = $mp_video;
}
elseif (stripos($mp_video, "h_360") !== false) {
$links['360p'] = $mp_video;
}
elseif (stripos($mp_video, "h_480") !== false) {
$links['480p'] = $mp_video;
}
elseif (stripos($mp_video, "h_720") !== false) {
$links['720p'] = $mp_video;
}
elseif (stripos($mp_video, "h_1080") !== false) {
$links['1080p'] = $mp_video;
}
}
}
one of my tests.
public function test_user_notExist_admin()
{
$client = new Client();
$response = $client->request('GET', 'https://www.example.com/api/user_days_and_roles?u=' . request()->uid);
$json = \GuzzleHttp\json_decode($response->getBody()->getContents(), True);
$this->get('/api/v1/exampledl?uid=1&n_id=400&u_ip=104.58.1.45&dl_id=a81498a9')
->assertStatus(200)
->assertSee('links');
$this->assertDatabaseHas('users', [
'uid' => (int)request('uid'),
'subscription.role' => 'administrator',
]);
}
There are some other conditions check and I'm not sure how to mock these different situations.
Should I make unit test for every situations? Or is there any way to make guzzle in test environment return a custom response? Or any other way?
I got the answer.
for mocking a function in different situations it just needs to use $mock = \Mockery::mock and makePartial();
like this and it let us to make every return we want without execute the function:
public function test_user_notExist_admin()
{
$mock = \Mockery::mock(DownloadController::class, [
'get_download_links_from_download_server' => $this->links,
'post_details_to_log_server' => [200, "new"],
'connect' => [
"Roles" => [
"authenticated",
"subscriber"
]
, "days" => "38"
]
]
)->makePartial();
$this->get('/api/v1/exampledl?uid=1&n_id=400&u_ip=104.58.1.45&dl_id=a81498a9')
->assertStatus(200)
->assertSee('links');
$this->assertDatabaseHas('users', [
'uid' => (int)request('uid'),
'subscription.role' => 'administrator',
]);
}
I've created for each API call a method then I mocked them with Mockery in an Array.
Another way to mock functions one by one:
$mock = Mockery::mock(DownloadController::class)->makePartial();
$mock->shouldReceive('et_download_links_from_download_server')->andReturn('123465');
$this->app->instance(DownloadController::class,$mock);
I have a card, this card has tags. So a Card has many tags and a Tag belongsTo a Card.
A user fills a form. He gives both the information for the card aswell as the tags.
Now I need to give each tag the information 'card_id' so it can be connected.
Now is my problem that I don't know this 'card_id' yet because the database did not yet assign a id as they are both being created simultaneously.
My situation:
public function create(Request $request)
{
$this->validate($request,[
'function' => 'max:255',
'description' => 'max:255',
'rate' => 'max:255',
'location' => 'max:255'
]);
$card = new Card;
$card->user_id = Auth::id();;
$card->function = $request->function;
$card->description = $request->description;
$card->rate = $request->rate;
$card->location = $request->location;
// I also tried this: $card->tag()->saveMany($tagsArray); (Did not work)
$card->save();
$tagsArray = explode(',', $request->tagsarray);
foreach($tagsArray as $tagInput) {
$tag = new Tag;
$tag->card_id = 'Cant know this yet :(';
$tag->tag = $tagInput;
$tag->save();
}
return redirect('/page');
}
Does someone know how to go about this?
You may try something like this:
$card = new Card([
'card_name' => request()->get('card_name'),
'something_else' => request()->get('something_else')
]);
if($card->save()) {
$tags = [];
// Get the tag information from request
$tagsFromRequest[
['tag_title' => 'A Tag', 'tag_slug' => 'a_tag'],
['tag_title' => 'Another Tag', 'tag_slug' => 'another_tag']
];
foreach($tagsFromRequest as $tag) {
$tags[] = new Tag($tag);
}
$card->tags()->saveMany($tags);
}
Now, prepare your tags from request where each tag item should be an array as given above and I can't be more specific because you gave nothing that you've tried and which might help me to understand your scenario. Check the documentation.
I have an ajax request, but I need my response to redirect to a certain twig template. This is what I have:
$response = ['success'=>false];
return $this->view->render($resp, 'spotlight-results.twig',['data' => $response] );
The problem with this is I am receiving the page in the console, this is not replacing the page that makes the request. I don't know if I explained myself correctly...
I have found the answer:
$loader = new Twig_Loader_Filesystem('../templates/');
$twig = new Twig_Environment($loader);
$template = $twig->loadTemplate('spotlight-results.twig');
$message = ['success' => false];
$view = $template->render(['data' => $message]);
$response = ['success' => false, 'view' => $view];
This way I return my template, with my desired content, $message