I am a newbie in Laravel MongoDB I would like to mention a problem here, outline of my Mongo document should be like
{
_id:****,
subscriptions: [{list_id: "14Q3"},
{list_id: "153"}],
offers: [ { targetURL: "www.qwerty.com", title: "25% discount" },
{ targetURL: "www.abcd.com", title: "55% discount" } ],
}
I have used the following code to insert a list id (was successful).
DB::connection('mongodb')->collection('subscribers')->insert(array(
'_id' => $subscriber->device_id,
'subscriptions' => array('list_id' => $subscriber->list1_id),
));
But when I try to push another list_id as next object it is showing error. I used the following code for pushing
DB::connection('mongodb')->collection('subscribers')
->push('subscriptions', array('list_id' => $subscriber->list1_id));
I don't know whether my code is right or wrong. I need to store the data as the outline given above. This is My actual problem. Please correct me....
My controller is is given below, I create new collection for each subscriber. Problem is second 'if' statement
public function store() {
$newsubscriber = Input::json();
//DB::connection('mongodb')->collection($newsubscriber->get('device_id'))->delete();
$result = Subscriber::where('list1_id',$newsubscriber->get('list_id'))->where('device_id',$newsubscriber->get('device_id'))->get();
if (!$result->isEmpty()) {
return "You are already a subscriber of this List";
}
else{
$result1 = Subscriber::where('device_id',$newsubscriber->get('device_id'))->get();
$subscriber = new Subscriber();
$subscriber->list1_id = $newsubscriber->get('list_id');
$subscriber->device_id = $newsubscriber->get('device_id');
$subscriber->subtype = 1;
$subscriber->save();
if (!$result1->isEmpty()) {
DB::connection('mongodb')->collection($subscriber->device_id)->push('subscriptions', array('list_id' => $subscriber->list1_id));
return "Subscribed successfully 1";
}
else{
DB::connection('mongodb')->collection($subscriber->device_id)->insert(array('_id' => $subscriber->device_id,'subscriptions' => array('list_id' => $subscriber->list1_id),
));
return "Subscribed successfully 2";
}
}
}
First i have used following API
curl -H "Content-Type: application/json" -d '{"list_id":"2","device_id":"987654321"}' http://localhost/lemmeknw/public/index.php/api/v1/subscribe
This returned "Subscribed successfully 2"
but when I used API for second time
curl -H "Content-Type: application/json" -d '{"list_id":"1","device_id":"987654321"}' http://localhost/lemmeknw/public/index.php/api/v1/subscribe
There was error "Something went wrong"
I don't know much about Laravel, but what I'm seeing here:
DB::connection('mongodb')->collection('subscribers')->insert(array(
'_id' => $subscriber->device_id,
'subscriptions' => array('list_id' => $subscriber->list1_id),
));
Looks like you are creating subscriptions as an object {list_id: <subscriber-list1_id>} instead of an array of one object [{list_id: <subscriber-list1_id>}]. So when you try to use the push operation
DB::connection('mongodb')->collection('subscribers')
->push('subscriptions', array('list_id' => $subscriber->list1_id));
that is an attempt to push to an object, not an array. My guess is that you will need to modify your insert to be
DB::connection('mongodb')->collection('subscribers')->insert(array(
'_id' => $subscriber->device_id,
'subscriptions' => array(array('list_id' => $subscriber->list1_id)),
));
Related
I am tring to insert multiple data in db using postman but only single data is insetred successfully ,when inserting multiple data getting 500 error.Please help me on how can i insert multiple data in db.Any help would be highly appreciated.Thank you.
PostMan raw data:
[{
"total_sales":"14",
"total_product":"21",
"total_profit":"5099",
"total_distributor":14,
"total_ratail":40 },
{
"total_sales":14,
"total_product":21,
"total_profit":50,
"total_distributors":14,
"total_ratail":40 }
]
Below is my code:
public function create()
{
$model = new AdminModel();
print_r("total_sales");
$data = array(
'total_sales'=>$this->request->getVar('total_sales'),
'total_product'=>$this->request->getVar('total_product'),
'total_profit'=>$this->request->getVar('total_profit'),
'total_distributors'=>$this->request->getVar('total_distributors'),
'total_ratail'=>$this->request->getVar('total_ratail'),
);
$query = $model->where('id', $data['total_sales'])->find();
if(count($query)>0){
$model->update->where('id', $data['total_sales'])->find();
}
else{
$model->insert($data);
}
//$model->insert($data);
$response = [
'status' => 200,
'error' => null,
'messages' => [
'success' => 'Data Saved'
]
];
return $this->respondCreated($response);
}
You are adding an array of objects but the code is expecting only one object. That's why you are getting the error.
You have to modify your php code to accept an array and loop through them.
My goal is to share a document/file with another user.
I am using https://learn.microsoft.com/en-us/graph/api/driveitem-invite?view=graph-rest-1.0&tabs=http to do it.
Error I have:
Client error: POST https://graph.microsoft.com/v1.0/me/drive/root:/operations.xlsx:/invite resulted in a 400 Bad Request response: {"error":{"code":"BadRequest","message":"The request is malformed or incorrect. Expected array for value of property: Collection(microsoft.graph.driveRecipient)","innerError":{"date":"2022-03-08T10:48:30","request-id":"xxx-xxxx-xxxxx","client-request-id":"xxx-xxxx-xxxxx"}}}
Find below my code:
operations.xlsx is the file I am trying to share.
public function send(){
$viewData = $this->loadViewData();
$graphs = $this->getGraph();
$body = array(
"requireSignIn"=> true,
"sendInvitation" => true ,
"roles" => "[write | read]",
"recipients"=>array(
"email"=> "person#email.com"
),
"message"=> "Here is the file."
);
$graphs->createRequest("post", "/me/drive/root:/operations.xlsx:/invite")
->attachBody($body)
->execute();
return response()->json($graphs);
}
I am using Laravel for the project.
public function sended(){
$viewData = $this->loadViewData();
$graphs = $this->getGraph();
$body = array(
"requireSignIn"=> true,
"sendInvitation" => true ,
"roles" => ["read"],
"recipients"=>array([
"email"=> "person#email.com"
]),
"message"=> "Here is the file."
);
$graphs->createRequest("post", "/me/drive/root:/operations.xlsx:/invite")
->attachBody($body)
->execute();
return response()->json($graphs);
}
I am using laravel apiResources for an api call, the problem is that i created a custom method named closePeriod, that when i try to fetch a period it return always
No query results for model [App\Entities\Accounting\Period]
this is the method, i try to get the Period with Period::findOrFail($id), i have checked and $id has a value, and it exists in the database
Route::get('periods/close/{id}', 'PeriodController#closePeriod');
public function closePeriod($id) {
if($period = Period::findOrFail($id)) {
//do something
return response()->json([
'error' => false,
'data' => $period
]);
}
return response()->json([
'error' => true,
'message' => 'The period was not found, please reaload and try again'
]);
}
I have noticed that the api methods does work fine, i get the periods in index, show and can create and edit a period so i think the problem is in the custom method? why?
My application: My application allows users to predict the scores of all upcoming soccer games for the next matchday. I get this data from an API and store the upcoming games in my database. These upcoming games have a status of Scheduled. Now I want to run a cronjob every few minutes that checks if the status of those matches have been changed to in_play or finished, if this is the case I want to update my status field in my database for the correct match to the status field from the api.
How can I check if the status has been changed and modify the correct match in my database? I have a match_id stored which can maybe be used for this?
My code:
updateStatus job
public function handle()
{
$this->updateStatus();
}
public function updateStatus() {
$this->getMatches();
// check if status has been changed from schedulded to 'in_play' or 'finished'
// update the match status of the right matches in my database
}
public function getMatches() {
$client = new Client();
$uri = 'http://api.football-data.org/v2/competitions/PL/matches/?matchday=12&season=2018&matches';
$header = ['headers' => ['X-Auth-Token' => 'My-token']];
$res = $client->get($uri, $header);
return json_decode($res->getBody()->getContents(), true);
}
getMatches job (this job gets the api data and stores it in the database)
public function handle()
{
$this->saveMatches();
}
public function saveMatches()
{
$matches = $this->getMatches();
collect($matches['matches'])
->each(function ($match, $key) {
$date = new DateTime($match['utcDate']);
Match::create([
'match_id' => $match['id'],
'homeTeam' => $match['homeTeam']['name'],
'awayTeam' => $match['awayTeam']['name'],
'status' => $match['status'],
'date' => $date->format('Y-m-d'),
'time' => $date->format('H:i'),
'matchday' => $match['matchday'],
'homeScore'=> $match['score']['fullTime']['homeTeam'],
'awayScore'=> $match['score']['fullTime']['awayTeam']
]);
});
}
public function getMatches()
{
$client = new Client();
$uri = 'http://api.football-data.org/v2/competitions/PL/matches/?matchday=12&season=2018&matches';
$header = ['headers' => ['X-Auth-Token' => 'My-token']];
$res = $client->get($uri, $header);
return json_decode($res->getBody()->getContents(), true);
}
What you probably want to do is utilize Laravel's updateOrCreate() method on your Match object. The uniquely identifying information appears to be the match id. If this doesn't ever change, then when you are looping through your each statement you can do this:
Match::updateOrCreate([
'id' => $match['id'],
],[
'homeTeam' => $match['homeTeam']['name'],
'awayTeam' => $match['awayTeam']['name'],
'status' => $match['status'],
'date' => $date->format('Y-m-d'),
'time' => $date->format('H:i'),
'matchday' => $match['matchday'],
'homeScore'=> $match['score']['fullTime']['homeTeam'],
'awayScore'=> $match['score']['fullTime']['awayTeam']
]);
What this does is look for an existing match with this same ID. If it already exists, it will simply update it with all of the information provided by the API, including the status of the match and the scores. If it doesn't yet exist, it will instead create it and store it in the database as a new match with all of the provided information. Hope this helps!
Hi everyone I need help with this problem. I am programming an application using php with laravel framework. My current laravel framework version is 4.2.11
I have this route to handle POST & GET actions
Route::any("/myaccount2/ausersave/{code?}", array("as" => "ausersave",
"uses" => "PrivateController#ausersave"))->before('auth_admin');
When I use Get action with mydomain/myaccount2/ausersave/90
I get list all data ok. But when I post all data to save the url change to mydomain/myaccount2/ausersave (parameter 90 is missing)
I guest this change is before the data is saved because the {code?} or 90 parameter is missing.
So I was looking for a function that allowed my application to post data and keeps the old url (mydomain/myaccount2/ausersave/90)
I find this function Redirect::back() but some post don't recommend to use it
I will apreciate your help. Thanks
My controller function is:
public function ausersave($code = 'null') {
$messg = null;
if(Input::get("userid") != null && Input::get("personid") != null) {
return View::make('PrivateController.ausersave', array('message' =>'Ok',
'user' => null, 'children' => null));
}
else if(isset($code)) {
return View::make('PrivateController.ausersave',
$this->ausersaveGet($code) );
}
return View::make('PrivateController.ausersave',
array('message' => '', 'user' => null,
'children' => null));
}
$this->ausersaveGet($code) -> this function bring me data form database and return me an array with thosse values array('message' => '', 'user' => $user, 'children' => $children); where user has info about user and children is an array of data. All this data return ok.
I would try taking the the ? out of the route parameter. i.e. change this:
Route::any("/myaccount2/ausersave/{code?}", array(......
to this:
Route::any("/myaccount2/ausersave/{code}", array(......