how to append user input to Http get request in Laravel 9 - laravel-9

Thank you in advance for taking the time to read through my question.
I'm upgrading an old project from Laravel 8 to Laravel 9
in laravel 8 i was able to append user input to a get request like this :
public function fetch(Request $request)
{
$userInput = $request->input();
$response = Http::withHeaders(
[
"x-rapidapi-host"=> "some.api",
"x-rapidapi-key"=> "**************",
]
)->get("https://some.api.com",$userInput);
$data = json_decode($response,true);
return view('view',compact('data'));
}
but when i try to do the same process in Laravel 9 i'm getting an error:
Invalid request
edit: (using dd() to show more error details about the response I'm getting)
array:4 [▼ // app\Http\Controllers\apiController.php:29
"searchType" => "Title"
"expression" => null
"results" => []
"errorMessage" => "Invalid request. See more information at https://theapiI'mUsing.com/api#/{lang?}/API/Search/{expression} - Search APIs: Search, SearchTitle, SearchName, SearchEpisod ▶"
]
I'm not able to send the data to the controller i guess? expression is showing null
although I was able to accomplish my goal using the same code in laravel 8
I have tried to append the input like this:
$response = Http::get("https://some.api.com/apiKey", [
'input' => $userInput,
]);
but also got the same error!
Invalid request
edit:
I have Also tried to concatenate the url with the user input
but got this error:
Array to string conversion
What is the proper way to append user input to a get request in Laravel 9?

Related

Laravel 8 save integer into null DB column - save vs update

I'm having an interesting issue where Laravel's save() does not replace null values in database, while the update() does. I also tested by manually changing null to 1 and afterwards the save() started updating the column. I am using save() throughout the project and would prefer that it stays that way or that at least I understand the problem before I go changing the code.
Migration (all codes will be partial extracts for brewity):
$table->foreignId('checklist_id')->nullable()->constrained('checklists')->onUpdate('cascade')->onDelete('cascade');
$table->foreignId('action_id')->nullable()->constrained('actions')->onUpdate('cascade')->onDelete('cascade');
Model (added the checklist_id and action_id for testing, otherwise they are not here):
// test
protected $fillable = [
'checklist_id',
'action_id',
];
protected $casts = [
'checklist_id' => 'integer',
'action_id' => 'integer',
];
// actual
protected $fillable = [
];
protected $casts = [
];
Controller:
public function update(UpdateWorkOrderRequest $request, WorkOrder $workOrder)
{
$response = $workOrder->save($request->all());
}
Form submission (from Chrome):
------WebKitFormBoundary73Z4wzsmsGcgOOAM
Content-Disposition: form-data; name="checklist_id"
1
------WebKitFormBoundary73Z4wzsmsGcgOOAM
Content-Disposition: form-data; name="action_id"
1
dd($request->all()):
array:2 [▼
"checklist_id" => "1"
"action_id" => "1"
]
The fields checklist_id and action_id are null after using save(), but they do get updated using update(). It's also working if I do this:
$workOrder->checklist_id = $request->checklist_id;
$workOrder->action_id = $request->action_id;
$workOrder->save();
I opted for save() to write less code instead of above example and because from docs I presume I can use save() when assigning data from $request, like here: https://laravel.com/docs/9.x/eloquent#updates
As discussed in the comments, you're trying to use model->save(attributes).
The save function does not provide any parameters for this. (docs).
You have two options, either use the model->update function (docs):
$workOrder->update($request->all());
Or use the model->fill (docs) function in combination with model->save like so:
$workOrder->fill($request->all())->save();

Regarding Bigquery datasetId and tableId

How do I get the datasetId and tableId from BigQuery. I tried to click the dropdown on the sidebar and copied the dataset info and table info, Is there any way, I can query the datasetId and tableId? but I got this error. I am using php client libraries to pull the BigQuery data.
How do I get the datasetId and tableId from BigQuery. I tried to click the dropdown on the sidebar and copied the dataset info and table info, Is there any way, I can query the datasetId and tableId? but I got this error. I am using php client libraries to pull the BigQuery data.
use Google\Cloud\BigQuery\BigQueryClient;
/** Uncomment and populate these variables in your code */
// $projectId = 'The Google project ID';
// $datasetId = 'The BigQuery dataset ID';
// $tableId = 'The BigQuery table ID';
// $maxResults = 10;
$maxResults = 10;
$startIndex = 0;
$options = [
'maxResults' => $maxResults,
'startIndex' => $startIndex
];
$bigQuery = new BigQueryClient([
'projectId' => $projectId,
]);
$dataset = $bigQuery->dataset($datasetId);
$table = $dataset->table($tableId);
$numRows = 0;
foreach ($table->rows($options) as $row) {
print('---');
foreach ($row as $column => $value) {
printf('%s: %s' . PHP_EOL, $column, $value);
}
$numRows++;
}
I am getting this error.
Google\Cloud\Core\Exception\BadRequestException : {
"error": {
"code": 400,
"message": "Invalid dataset ID \"mc-data-2:Turnflex\". Dataset IDs must be alphanumeric (plus underscores and dashes) and must be at most 1024 characters long.",
"errors": [
{
"message": "Invalid dataset ID \"mc-data-2:Turnflex\". Dataset IDs must be alphanumeric (plus underscores and dashes) and must be at most 1024 characters long.",
"domain": "global",
"reason": "invalid"
}
],
"status": "INVALID_ARGUMENT"
}
}
According to PHP Google Cloud client library documentation for a proper BigQueryClient() class initialization you might be requiring propagate $projectId variable. In case of any Biqguery data querying or discovering action aimed, you would probably leverage query() method submitting Bigquery Job with the particular custom query or explicitly define dataset() and table() as the target Bigquery location.
Confirming #Priya Agarwal presumption, I've checked the code snippet from your example and it works as intended. I've catched the similar error that you've reported, once I made connection with $datasetId variable exposed jointly with tableId:
$datasetId = 'datasetId:tableId'
instead of:
$datasetId = 'datasetId'

How to turn string output from sql to integer?

I am generating charts using google chart api. I have done it locally and successfully produce the charts. However, when I transfer them to server (cpanel) the charts is ruined. I have detected that the output of sql query for generating the charts value is produced in string format with "6".
This is the code to get the charts' value:
public function gender()
{
$data = DB::table('results')
->select(
DB::raw('gender as gender'),
DB::raw('count(*) as number'))
->groupBy('gender')
->get();
//dd($data);
$array[] = ['Gender', 'Number'];
foreach($data as $key => $value)
{
$array[++$key] = [$value->gender, $value->number];
}
//dd($array);
return view('gender')->with('gender', json_encode($array));
}
In my local, I try to access the data of the sql using dd($data); producing:
Collection {#263 ▼
#items: array:2 [▼
0 => {#264 ▼
+"gender": "female"
+"number": 6
}
1 => {#266 ▼
+"gender": "male"
+"number": 6
}
]
}
I tried accessing in server using same dd($data);
Collection {#260 ▼
#items: array:2 [▼
0 => {#261 ▼
+"gender": "female"
+"number": "6"
}
1 => {#263 ▼
+"gender": "male"
+"number": "6"
}
]
The difference is the number value from server code is in string.
Why this happened and how to fix the problem?
I had a similar issue. It seems it's a PHP issue. Are you running the same PHP versions on local and production?
In any case, you could also explicitly cast it as an UNSIGNED integer. I was able to do that with the following:
$data = DB::table('results')
->selectRaw('gender as gender, CAST(count(*) AS UNSIGNED) as number')
->groupBy('gender')
->get();

Karate - actual value is not a string

I am checking for an 'OK' parameter in response but getting above mentioned error. The same code was working with my previous karate version, now I am using 0.9.0 - This might be some issue with my coding, can't figure out.
Response:
"testResponse": {
"planSummary": {
"includedServicesList": [
{
"some elements goes here": "test"
}
],
"status": {
"statusCd": "200",
"statusTxt": "OK"
}
}
}
My Feature File Code:
When method get
Then status 200
Then match response contains 'OK'
I get expected: 'OK', reason: actual value is not a string error.
I tried with Then match response contains {statusTxt: 'OK'} as well.
You can try this,
* match response.testResponse.planSummary.status contains {'statusTxt' : 'OK'}
OR
* match response.testResponse.planSummary.status.statusTxt == 'OK'

Backbone.js and ActiveRecord

This is a Noob question regarding Backbone.JS and ActiveRecord.
I'd be grateful for a pointer on how to debug this.
I'm trying to use Backbone.Js code to create a "Trainer" object, which has a single attribute, "name" (a string).
The front end of the application is Ruby on Rails. There is a data migration for the Trainer table.
In trainers controller:
def create
document = Trainer.create! params[:trainer]
render :json => document
end
Now, in app/assets/javascripts/backbone/views/trainers/new_view.js:
Gym.Views.Trainers.NewView = Backbone.View.extend({
el : 'div.trainer_form',
template: JST['backbone/templates/trainers/new_template'],
model : new window.Gym.Models.Trainer({}),
initialize: function() {
this.document = this.options.user;
Backbone.Validation.bind(this, {
invalid: function(view, attr, error) {
$("form#new-trainer .errors ul").append("<li>" + error + "</li>")
}
});
this.render();
},
render : function() {
$(this.el).html(this.template({trainer:this.model.toJSON()}));
return this
},
events : {
"click input#submit_button" : 'create_trainer'
},
create_trainer : function(event) {
event.preventDefault()
params = $("form#new-trainer").formParams()
params['user_id'] = Gym.currentUser.userId
this.model.save(params, {success : function(model, response) {
Gym.trainers.add(model)
Objects.views.selectTrainer.render()
Gym.current_trainer = model
$("select#trainer_selector").val(Gym.current_trainer.get('id'))
Objects.views.new_trainer.model = new Gym.Models.Trainer()
Objects.views.new_trainer.render()
}
});
Now, I can see in the Rails log that I'm getting to the controller:
Started POST "/trainers" ...
Processing by TrainersController#create as JSON
Parameters: {"name"=>"Lori Stevens", "user_id"=>1, "trainer"=>{}}
However, when it gets to the SQL, I see this:
[1m^[[36mSQL (0.4ms)^[[0m ^[[1mINSERT INTO `trainers` (`created_at`, `name`, `updated_at`, `user_id`) VALUES ('2012-11-07 20:33:09', NULL, '2012-11-07 20:33:09', NULL)^[[0m
The parameter 'name' - which comes from the template, and is the attribute of the Trainer object- is not getting to the database, even though the parameter "name" is set in the JSON.
I'd appreciate a pointer on how to debug this - clearly I am not understanding how Backbone.js and ActiveRecord are connected.
The Controller takes the request from your browser and puts the data into ActiveRecord:
def create
document = Trainer.create! params[:trainer]
...
end
But then you see request in the log, params[:trainer] equals the empty hash {}
You can either change the javascript that it creates json with a hash like
{ 'trainer': {'name' : 'Lori stevens', ... }}
I don't know how easy this in backbone.
Or you can change your controller that it gets the values out of the hash and constructs an new hash for your trainer model, like it is:
gotten_name_from_json = params['name']
...
document = Trainer.create!(
{:name => gotten_name_from_json, :town => gotten_twon_from_json})
I made this verbose to show that using this you can translate what ever json comes in, even when it comes from third parties where you can not control the format.