How to save data through objects which are in array in Laravel - php

I m newbee in laravel. I am sending such type of response through Postman. and in Laravel controller I m getting this response in $request.
[{
"id": 40,
"cname": "Ramesh",
"constraint_value": "",
"r_id": "6",
"rtype_id": null,
"deleted_at": null,
"created_at": null,
"updated_at": null,
"input": "111",
"input2": "111"
}, {
"id": 45,
"cname": "Suresh",
"constraint_value": "",
"r_id": "6",
"rtype_id": null,
"deleted_at": null,
"created_at": null,
"updated_at": null,
"input": "222",
"input2": "222"
}, {
"id": 49,
"cname": "Raj",
"constraint_value": "",
"r_id": "6",
"rtype_id": null,
"deleted_at": null,
"created_at": null,
"updated_at": null,
"input": "333",
"input2": "333"
}]
I am facing difficulty in
How to count the total no of objects in array which I am receiving in $request. I had used count($request) or sizeOf($request) but its returning only 1 although there are 3 arrays. Help me in this.
How to save the data in database through such arrays.I want to save the values of input and input2.

Probably late, but may help someone in the future. First of all. You need to iterate over the array of objects like so
foreach($request->all() as $key => $value){
$model = new Model();
$model->attribute1 = $value['attribute1'];
$model->attribute2 = $value['attribute1'];
$model->attributeN = $value['attributeN']; // where N is infinite # of attr
$model->save();
}
So what is happening is that each time the loop iterates, it create a new object of your Model type inside the loop and assigns the objects attributes from the array key values and persists in DB and repeats until all the objects in the array are finished. The
$model = new Model();
is necessary so that each time loop iterates It creates a new object and persists. The loop may save only one object if u do not create it each time the N iteration occurs. This may happen if u are creating the model object in the constructor where it is instantiated once when the constructor is run.
Hope this helps.

Try to convert it to an array:
$data = json_decode($request, true);
$count = count($data); // Count number of elements.
Model::insert($data); // Insert all elements into DB.
Don't forget to validate any input first and add all fields except timestamps to a $fillable array.

You can try this..
$data = [{},{}]; // your response
$count = 0;
foreach($data as $obj)
{
Model::create($obj); //save the model
$count ++;
}
echo $count // your count

its quit simple
$request ='[ {"id":40,"cname":"Ramesh","constraint_value":"","r_id":"6","rtype_id":null,"deleted_at":null,"created_at":null,"updated_at":null,"input":"111","input2":"111"}, {"id":45,"cname":"Suresh","constraint_value":"","r_id":"6","rtype_id":null,"deleted_at":null,"created_at":null,"updated_at":null,"input":"222","input2":"222"}, {"id":49,"cname":"Raj","constraint_value":"","r_id":"6","rtype_id":null,"deleted_at":null,"created_at":null,"updated_at":null,"input":"333","input2":"333"}]';
$request = (array)json_decode($request, true);
now use them as you usually use .

I got the solution. I was making mistake in sending the data from angularjs.I was directly sending the POST request without creating its object like var data = { 'data':my_request} .That is why request was reeving with instance in laravel. But, as I start sending data by creating its object its working. This was the solution for my first problem. Help me how to store that received data in database.

Related

Get whole object data instead id in Laravel

I have an object with this structure, that I need to get name of source_id in my blade file,
When I try to access that by the way
$data['source_id']['name']
$data->source_id->name
$data->{'source_id'}->{'name'}
I got this error
Trying to get property 'name' of non-object
I just try this $data->source_id, but it return its ID, instead the object,
any suggestion?
{
"id": 4,
"type": "s1",
"source_id": {
"id": 1,
"code": "۱",
"name": "تیل پطرول",
"manager": "نجیب",
"phone": "۰۷۷۲۴۳۴۳۲۱",
"address": "دهمزنگ",
"capacity": "0.00",
"oum_id": 1,
"created_at": "2021-03-02T15:55:20.000000Z",
"updated_at": "2021-03-02T15:55:20.000000Z"
},
"source_type": "STRG",
}
Here is the function to get data
public function loadSale($id){
$base = Sale::findOrFail($id);
if ($base->type == "s1") {
$sale = Sale::with(['saleS1.project.pro_data', 'source_id'])->where('id', $id)->first();
$sale['sales'] = $sale->saleS1;
}
return $sale
}
I could understand your problem. But it is an object not an array. You have to use a loop to access the object. Create a for loop and and inside which you can access the particular field of the object. Hope this helpful
As #MAY mentioned in the comment
I guess the name of your relation and foreign key field is same, that's why you get id when you do this $data->source_id
So I modify the relation and define the source, now I can't access the data simply as before $data->source->name

Codeigniter - filtering json data by user request

So, I have table ($data) with JSON records getting by select query.
for example:
"data": {
"id": "1",
"technology_name": "First",
"technology_info": "Something about first rec",
"created_at": null,
"updated_at": null
},
{
"id": "2",
"technology_name": "Second",
"technology_info": "Something about second rec",
"created_at": null,
"updated_at": null
}
}
...
Now I need to create filter by column (technology_name) by user request with 'like', something like
select * from "data" where technology_name = '%css%';
It is possible to do this with CodeIgniter/PHP code and JSON file, or is better way to do that? Can you give me some advice how to figure it out?
I think that I misspelled my problem.
I was able to find the correct solution.
So, I modified my script that return response as JSON representation with some instructions that SELECT data with WHERE by getting user request params.

Laravel - Eloquent to Json, and then sortBy on json object not working

I have this json value that I want to be sorty but for some reason it's not working.
[
{
"id": 15028,
"order_id": 342,
"user_id": 3,
"status": "1",
"priority": "1",
"donedate": null,
"user": {
"id": 3,
"name": "Max"
}
},
{
"id": 15030,
"order_id": 341,
"user_id": 4,
"status": "2",
"priority": "1",
"donedate": null,
"user": {
"id": 4,
"name": "Jon"
}
}
]
This jSon structure is the result of Laravel eloquent object conversion using $object->toJson();
Now I keep this output in my Redis cache. What I want is to when the status and or priority of any order gets changed then I want to sort this jSon and store it back in Redis.
$order_list = collect($json_decoded_with_updated_values);
$order_list = $order_list->sortBy('status')->sortBy('priority');
Redis::set(\GuzzleHttp\json_encode($stich_list_in_collection));
Redis::set("orders_list", $orders_list, 302400);
However, I don't get a sort list. What I want to achieve is that, just like I would run two to three orderBy on an eloquent model like orderBy('status')->orderBy('priority')->get() .. I want to run the same two sortings on this json list.
Thanks in advance.
I figured it out. Actually we don't need to have a call-back as suggested by #brokedid. We can do it like following.
$order_list->sortBy('status')->sortBy('priority')->values()->all();
So I was missing the "->values()->all()" part. I hope if any one runs into the same problem in future, they can get a hint from this.
If you want to sort by multiple Fields, then you could try to sort with a callback-method:
$orderedList = $unorderedList->sortBy(function($item) {
return $item->priority.'-'.$item->status;
});
I wonder what's the result when you choose a different sort direction.
$order_list = $order_list->sortByDesc('status');

Search multidimensional array with Key name and return values as result

I am PHP beginner so please be patient with me. I spent couple of hours going through many threads already on multidimensional arrays search but none of them fits my situation. Sounds really simple but kind of stuck as I want to search by key name and retrieve values against it.
Tried some methods like array_column but returns an empty array.
I simply want to loop through array finding key name as: "largeImageURL" from all the array elements and want to return its values.
{
"total": 4692,
"totalHits": 500,
"hits": [
{
"id": 195893,
"pageURL": "https://pixabay.com/en/blossom-bloom-flower-195893/",
"type": "photo",
"tags": "blossom, bloom, flower",
"previewURL": "https://cdn.pixabay.com/photo/2013/10/15/09/12/flower-195893_150.jpg"
"previewWidth": 150,
"previewHeight": 84,
"webformatURL": "https://pixabay.com/get/35bbf209e13e39d2_640.jpg",
"webformatWidth": 640,
"webformatHeight": 360,
"largeImageURL": "https://pixabay.com/get/ed6a99fd0a76647_1280.jpg",
"fullHDURL": "https://pixabay.com/get/ed6a9369fd0a76647_1920.jpg",
"imageURL": "https://pixabay.com/get/ed6a9364a9fd0a76647.jpg",
"imageWidth": 4000,
"imageHeight": 2250,
"imageSize": 4731420,
"views": 7671,
"downloads": 6439,
"favorites": 1,
"likes": 5,
"comments": 2,
"user_id": 48777,
"user": "Josch13",
"userImageURL": "https://cdn.pixabay.com/user/2013/11/05/02-10-23-764_250x250.jpg",
},
{
"id": 73424,
...
},
...
]
}
First of all, you have to convert your JSON object to an array and compare like below.
$results = json_decode($your_array);
$match_result = [];
foreach($results['hits'] as $result) {
if (isset($result['largeImageURL']) {
$match_result [] = $result['largeImageURL'];
}
}
print_r($match_result);
You have to decode your JSON response into an array and loop through hits array till you find the key and return the data.
$returnArr = array();//to store values of largeImageURL
$json = "<json response>";//your json string here
$decoded_json = json_decode($json, true);//convert json to an array
//now we will loop through hits
foreach($decoded_json['hits'] as $hit){
$returnArr[] = $hit['largeImageURL'];
}
print_r($returnArr);

Search an array nested in a laravel collection

I have a api call that returns a set of data something like this:
{
"id": 97423,
"visitor_id": 231505,
"domain_sessionidx": 1,
"session_start": "2017-06-01 04:40:07",
"session_end": "2017-06-01 05:22:45",
"session_length": 2558,
"count_pages": 11,
"count_pings": 7,
"created_at": null,
"updated_at": "2017-06-12 18:59:51",
"pages": [
1829,
1811,
1829,
1501,
1829,
1889,
1762,
1686,
1825,
1825,
1825
] },....
I have put this into a variable and made a collection out of it:
$new_var = collect($result);
I am having a problem because I would like to access only the records in the data where pages contains the id 1762. I have been trying with:
$new_var->whereIn('pages',[1762])->pluck('pages')
but I am always getting an empty result. Any help is greatly appreciated.
I feel like you need to filter your $new_var collection and return true if it's pages attribute contains the page you are looking for. For example:
$page = 1762;
$inPages = $new_var->filter(function($collection) use($page){
return in_array($page, $collection->pages);
});
$inPages should now be a subset of $new_var with entries that contain 1762 in their pages array, otherwise it will be an empty Collection. Check here for more information: https://laravel.com/docs/5.4/collections

Categories