How to set Updates to this data - Laravel/Lumen - php

I have a web application where the user shall be able to change MariaDB records via a GUI inside the browser.
In this GUI, the user sees a list of the records visible for him. Whatever he can see, he has permission to delete or change as well.
To change a DB record, he simply has to click the fields he wants to change inside the list and then press the "send" button.
In his HTTP request, the id associated with the record will be transmitted so the backend can identify the respective record inside the DB and apply the changes.
Now, Im rather new to Laravel/Lumen. To fetch the list the user can apply changes to in the first place, I have the following code:
$join = coretable::with($permittedTables)->get();
The $permittedTables is an array of tablenames, so any number or combination of tables might be joined to coretable.
For example, a fetch can look like this:
[{
"Internal_key": "TESTKEY_1",
"extensiontable_itc": {
"description": "EXTENSION_iTC_1"
},
"extensiontable_sysops": {
"description": "EXTENSION_SYSOPS_1"
}
}, {
"Internal_key": "TESTKEY_2",
"extensiontable_itc": {
"description": "EXTENSION_ITC_2"
},
"extensiontable_sysops": {
"description": "EXTENSION_SYSOPS_2"
}
}, {
"Internal_key": "TESTKEY_3",
"extensiontable_itc": {
"description": "EXTENSION_ITC_3"
},
"extensiontable_sysops": {
"description": "EXTENSION_SYSOPS_3"
}
}, {
"Internal_key": "TESTKEY_4",
"extensiontable_itc": {
"description": "EXTENSION_ITC_4"
},
"extensiontable_sysops": {
"description": "EXTENSION_SYSOPS_4"
}
}, {
"Internal_key": "TESTKEY_5",
"extensiontable_itc": {
"description": "EXTENSION_ITC_5"
},
"extensiontable_sysops": {
"description": "EXTENSION_SYSOPS_5"
}
}]
Now, I wondered if I could just reuse the code I've created to fetch the data for setting the data.
So I used the above shown $join and tried to determine the datarecords I want to change.
The attempt looks like this:
$join = $join->find("TESTKEY_1");
The find however doesnt return anything.
Considering the structure of the results I'm querying here, is this approach even feasible? Or should I build some new code, fetching the results in a different structure, better suited to have changes applied to it?
Still, is there a way to search these fetchresults for a subset of data and then apply changes to this subset (and persist those changes to the DB, of course)?

$join = $join->find("TESTKEY_1");
find method works only for ids.
e.g. $join = $join->find(1); //1 is id (primary_key) in here.
if you want to find the record by TESTKEY_1
$join = $join->where("Internal_key","TESTKEY_1")->get();
// will return array of all records having Internal_key TESTKEY_1
if you want only the first record to be fetched
$join = $join->where("Internal_key","TESTKEY_1")->first();
// will return only first having Internal_key TESTKEY_1 as an array.

Related

laravel 5.3 Many-to-Many relationship returns associated Role only when queried

I am just confused on how this thing is working .
I have a M-M relationship between by Users and Roles. If I retrieve my user like the following :-
$user = Auth::User();//->with('roles')->get();
$roleName = $user->roles[0]->name;
return $this->sendResponse('User retrieved successfully',$user);
I get the following response :
{
"success": true,
"message": "User retrieved successfully",
"data": {
"id": 2,
"name": "dummy",
"email": "dummy#dummy.com",
"created_at": "2017-05-06 09:49:50",
"updated_at": "2017-05-06 09:49:50",
"tenant_id": 2,
"roles": [
{
"id": 1,
"created_at": "2017-05-06 06:26:55",
"updated_at": "2017-05-06 06:26:55",
"name": "Admin",
"permissions": null,
"pivot": {
"user_id": 2,
"role_id": 1
}
}
]
}
}
But, if I retrieve my user as :-
$user = Auth::User();//->with('roles')->get();
return $this->sendResponse('User retrieved successfully',$user);
I get the following resut :-
{
"success": true,
"message": "User retrieved successfully",
"data": {
"id": 2,
"name": "Ali",
"email": "ali#and-or.com",
"created_at": "2017-05-06 09:49:50",
"updated_at": "2017-05-06 09:49:50",
"tenant_id": 2
}
}
Why is this happening ? I expected the "first" posted result to the latter query.
Secondly, I did not modify the $user after the query in the first "method" how did it get its Roles attachment ?
I am sure there is an explanation, but I couldn't put my finger on it.
When retrieving a model, the User in this instance, relationships are not automatically also retrieved (Since on the database side this would require a second query while you might not even need the roles in a certain situation).
In your first example, by accessing the roles through $roleName = $user->roles[0]->name;, Laravel does the roles() query automatically, and also adds the roles object to the User (So it can be accessed again at a later point without needing to redo the query). This explains why the roles are 'magically' attached to your User model in the first example.
In your second example this query is not done automatically, so you do not get the roles relation in your response.
If you want to have access to the Users roles, then you could use the with() method like in your comment to eager load the relationship, but keep in mind that this implies doing the second query in order to get this data from the database.
Another option, if you always want the User model to have its Roles attached, would be to add roles to the $appends array of the model:
protected $appends = ['roles'];
This tells Laravel that the roles attribute is one which you always want available on your model, and it then does what is necessary to make this happen (In this case, query the relationship).

How to extract data inside JSON response from Zoho CRM API

I'm working with the Zoho CRM. The response format I get from their API seems a bit odd to me; I can't just pull an object from it like I would normally. I'm trying to parse the results using PHP. Here's an example of their response formatting:
{
"response": {
"result": {
"SalesOrders": {
"row": {
"FL": [
{
"content": "6666666000000000000",
"val": "SALESORDERID"
},
{
"content": "Order",
"val": "Subject"
},
{
"content": "Pending",
"val": "Status"
},
{
"content": "John Smith",
"val": "Order Owner"
},
{
"content": "Canada",
"val": "Billing Country"
},
{
"product": {
"FL": [
{
"content": "5555555000000000000",
"val": "Product Id"
},
{
"content": "Roller Coaster",
"val": "Product Name"
}
],
"no": "1"
},
"val": "Product Details"
},
"content": "Pending",
"val": "Ticket Status"
}
],
"no": "1"
}
}
},
"uri": "/crm/private/json/SalesOrders/getRecordById"
}
}
What I'm trying to do is get the Product ID of the Product (in this case the value is "5555555000000000000".
Every response has the same structure, but I can't use the index to parse out the key/value because the amount of fields could change between API calls (meaning the index of product could be 5, like above, or 7, or 8, or whatever depending on the amount of fields being pulled in). I don't understand why they didn't use typical key/value pairs, such as "Product_ID": "5555555000000000000" which would make all of this a non-issue.
Is there a way to do this without iterating through every key/value pair looking for a "val" of "Product ID" and then grabbing the associated "content" (which is the product id I'm looking for)? That's the only way I could think of and it doesn't seem very efficient.
PHP has a function for that: json_decode. See http://php.net/manual/en/function.json-decode.php
$response = "... your JSON response from wherever ...";
$data = json_decode($response, true);
// Access the nested arrays any way you need to, such as ...
$orders = $data["response"]["result"]["SalesOrders"];
foreach ($orders["row"]["FL"] as $item) {
if (array_key_exists("product", $item) {
echo $item["product"]["FL"][0]["content"];
}
}
EDIT: Corrected 2nd arg to json_decode (thanks Marcin)
I don't understand why they didn't use typical key/value pairs, such as "Product_ID": "5555555000000000000" which would make all of this a non-issue.
Yes, there could be a key=>value pair, but that would be to easy.
Because Zoho ... ;)
Is there a way to do this without iterating through every key/value pair looking for a "val" of "Product ID" and then grabbing the associated "content" (which is the product id I'm looking for)?
No, (even if you turn this into an array using json_decode($data, true) and go forward by using named keys) you end up iterating or testing for key existence (need to get to product-FL-val to get product-FL-content). Maybe array_fiter or array_walk with a callback come to rescue, but they also iterate internally.
My suggestion is to simply safe some time and use an existing package, e.g.
https://github.com/cristianpontes/zoho-crm-client-php
or search one on Packagist https://packagist.org/search/?q=zoho
I dont know this might help or not. But this is what i am using for my Zoho APP. Actually I am developing a PHP app using Zoho. Your JSON and mine is same but i am getting Deals and you are fetching SalesORders.
<?php
$token = $_SESSION['token'];
$url = "https://crm.zoho.com/crm/private/json/Deals/getRecordById?authtoken=$token&scope=crmapi&id=$dealID";
$result = file_get_contents($url);
$deal_detail = json_decode($result);
$deal_detail = json_decode(json_encode($deal_detail), True);
$deal_detail_array = array();
//Instead of Deals you have SalesOrder right
foreach($deal_detail['response']['result']['Deals']['row']['FL'] as $array){
$deal_detail_array[$array['val']] = $array['content'];
}
echo $deal_detail_array['DEALID']; // You can change this to SALEORDERID, get data correctly every time.
echo $deal_detail_array['Deal Name'];
echo $deal_detail_array['Amount'];
///.......and so on ..............//
//................................//
Only the difference between your JSON and mine is: You have "SalesOrders" in your JSON after result field and in my json instead of SalesOrders i have Deals there.
this code is working fine for me. SO you can do same thing except a field update. I am getting DEALID correctly for each request similarly you can get you SALESORDERID

Update multiple mysql tables with one json in php

I've got an AngularJS frontend and got some problems relating the data layer.
In the frontend I've got contacts.
contact JSON object:
{
"id": 1,
"groupId": 1,
"firstName": "John",
"lastName": "Doe",
"email": "jd#gmail.com",
"company": "Google",
"info": "lorem ipsum dolor amet",
"numbers": [
{
"typeId": 1,
"number": "123456"
},
{
"typeId": 2,
"number": "1234567"
},
{
"typeId": 3,
"number": "8765432"
},
{
"typeId": 4,
"number": "0864235"
}
]
}
I get this object over an url with one http request.
When I will save it I give exactly this object back to the backend.
But how can I e.g. update a number out of the numbers table or the company out of the companies table with php?
My colleague said to me that when i update a number in the contact object, i have to call an url with /numbers/id .
But I just want to put back a "contact object" at /contacts
and let the business layer/data layer do the logic and split the object to update different tables.
In the backend he uses php and fat-free-framework.
Can anyone explain how to do this?
-EDIT-
And I thought the complete logic how to save the data is in the backend.
With DTO (Data Transfer Object) and DAO (Data Access Object) etc.
If you want to accept an object graph then you would need to parse it then make the appropriate calls to the database.
For example, presuming you have a table "numbers" that has columns "typeId" and "number" you would probably want logic in your "contact" class that does something like...
// convert the JSON to PHP
$request = json_decode($contact);
if(isset($request->numbers)) {
$number = new \DB\SQL\Mapper($this->db, "number");
// loop over your number objects
foreach($request->numbers as $data) {
// create a new number entry for each one
$number->copyfrom($data);
$number->save();
$number->reset();
}
}
Obviously how and where you do this would depend on how you have structured your code, for example contact->post() and contact->put() might be applicable places.

searching for a way to filter results by a field defined in another linked table using Doctrine and MongoDB

I need to find a way to filter results from a MongoDB database, based on fields found in the current table, and a field found in another table which is linked to the current table. Tables format:
{
"_id": ObjectId("51af256a0da4dd7804000007"),
"enddate": ISODate("2013-06-14T21:00:00.0Z"),
"main": false,
"name": "name 1",
"photo": "image-1.jpg",
"site": {
"$ref": "Sites",
"$id": ObjectId("51ac538c5f06751414bd9f98"),
"$db": "local"
},
"startdate": ISODate("2013-04-30T21:00:00.0Z")
}
{
"_id": ObjectId("51d3d5b9caa8213b12e92c5e"),
"sitefeatured": false,
"sitename": "a",
"sitephoto": "aa.jpg",
"siteurl": "aaaa.com/"
}
what i`m trying to do in ->where clause is to search in the string formed by this.name and this.site.sitename:
my problem is that i don't know / didn't find how to reference to property sitename of the site object
$entries = $dm
->getRepository($sTable)
->createQueryBuilder('o')
->where('function() { return ( (this.name + this.site.sitename).toLowerCase().indexOf("'.$_GET['sSearch'].'".toLowerCase()) !== -1 ) ? true : false }')
->sort($aColumns[$_GET['iSortCol_0']], $_GET['sSortDir_0'])
->limit($_GET['iDisplayLength'])
->skip($_GET['iDisplayStart'])
->getQuery()
->execute();
Is there anything like SQL join that i didn't came across, or what's the solution?

Looking for effiicient way to pull data from facebook graph api

I've been recently working with facebook graph api , when I'm pulling user's recents status messages using https://graph.facebook.com/me/statuses?access_token=... all I get is a long list which contains details about the status content, and I want to pull the names of people who liked the status.
The current solution I've been thinking about is using preg match,
I'd like to know if you guys have any other suggestions,
Thanks in advance
I'm not sure what path you're using, but you can fetch the list of users who like a particular status update by requesting the likes connection on an update.
For example, requesting https://graph.facebook.com/10150710880081168/likes yields something like the following for me:
{
"data": [
{
"id": "276700623",
"name": "Vikki Carter"
},
{
"id": "1514365200",
"name": "Darren Bean"
},
{
"id": "539760281",
"name": "Ian Sidaway"
}
],
"paging": {
"next": "https://graph.facebook.com/10150710880081168/likes?format=json&limit=25&offset=25&__after_id=539760281"
}
}
You'll need the ID of the status update, but also the user_status permission from the logged-in user.
EDIT: Iterating over the returned data and assigned users into an array:
<?php
$result = $facebook->api('[status_id]/likes');
$names = array();
foreach ($result['data'] as $user) {
$names[] = $user['name'];
}
You should now have an array of names of users who liked the status in question.

Categories