Laravel 5 - looping over a Collection - laravel-5

can't seem to figure this out. I have the following code
dd($this->project->dsReportingDoc->reportingDocUpload);
if(!empty($this->project->dsReportingDoc->reportingDocUpload)) {
dd("TEST");
foreach($this->project->dsReportingDoc->reportingDocUpload as $key){
}
}
Now the first dd prints out something like the following
Collection {#274 ▼
#items: array:2 [▼
0 => ReportingDocUpload {#275 ▶}
1 => ReportingDocUpload {#276 ▶}
]
}
So, there are two items in the Collection. However, the second dd never seems to get executed, so it must never make it into the if statement.
If anything is in the collection, I need to loop them and get a parameter. So I need to see if the item exists first.
Why would my if statement be failing here when it is not empty?
Thanks

The dd() debug function stops execution of the current request. So you can only call it once and get output - see here.
This is the reason your if condition and foreach aren't executing.

Try this
if($this->project->dsReportingDoc->reportingDocUpload) {
dd("TEST");
foreach($this->project->dsReportingDoc->reportingDocUpload as $key){
}
}
What you can do is, assign the
$this->project->dsReportingDoc->reportingDocUpload
to a variable so you don't have to rewrite it every where.

Related

How to get the State or Province using Geocoder Php

I'm wanting to reverse geocode coordinate to get the address using Geocoder-php. I'm able to get the Address Collection using $geo = app('geocoder')->reverse($lat, $lng)->get().
According to these docs found on github for Geocoder-php you can retrieve the properties form the collection, such as street name by using $geo->getStreetName(), the city by using $geo->getCity(), the country by using $geo->getCountry(), etc, but there are no methods for returning the State or Province.
How do I grab the state or province from the collection?
I can see the province when I use $geo->getAdminLevels()->get(). Which returns
AdminLevelCollection {#900 ▼
-adminLevels: array:2 [▼
1 => AdminLevel {#901 ▼
-level: 1
-name: "Saskatchewan"
-code: "SK"
}
2 => AdminLevel {#902 ▼
-level: 2
-name: "Division No. 16"
-code: "Division No. 16"
}
]
}
But I am unable to grab the province (Saskatchewan).
(I am using Laravel Geocoder for a Laravel project.)
EDIT:
$geo->getAdminLevels()->get(1) give me this
AdminLevel {#690 ▼
-level: 1
-name: "Saskatchewan"
-code: "SK"
}
But $geo->getAdminLevels()->get(1)->name; give me this error
Undefined property: Geocoder\Provider\GoogleMaps\Model\GoogleAddress::$getAdminLevels
The solution to this is to call it this way;
$geo->getAdminLevels()->get(1)->getName();
get() in this context takes a value of the index you wish to return.
You might want to check that the getAdminLevels() and get(1) return values if they may sometimes return nulls. You can do this by implementing something like !empty($geo->getAdminLevels())
You can do
$geo->getAdminLevels()->get()->adminLevels[0]->name or $geo->getAdminLevels()->get()->adminLevels[1]->name

Using dd() function in Laravel

While using dd() function in Laravel, if my output looks like this,
Collection {#194 ▼
#items: array:3 [▼
0 => Post {#195 ▶}
1 => Post {#196 ▶}
2 => Post {#197 ▶}
]
}
what are the meanings of the codes, such as #194, #195, etc? Are they helpful in any way?
According to VarDumper documentation - that's what dd() uses behind the hood:
#14 is the internal object handle. It allows comparing two consecutive dumps of the same object.
Depending on whether the item being dumped is an object or PHP resource, you'll see # for objects and # for resources in there. The number you're seeing after # is the ID assigned by the VarDumper to that object. It's displayed so that you can easily identify dumps for the same object, if you dump it multiple times.

Laravel Custom Collections

I'm trying to understand something. Consider the following:
$collection = collect(['example1' => 'test1', 'example2' => 'test2']);
When I do the following, I end up with this result:
Collection {#867 ▼
#items: array:2 [▼
"example1" => test1
"example2" => test2
]
}
What I want to be able to do is this:
echo $collection->example1 // Should display test1
But instead it says "Trying to get property of non object".
So, I have two questions:
Can somebody explain the above behaviour?
Can somebody help with a solution so I can do $collection->example1?
Collections are objects containing an array. If you look back at what you posted you can see that you have an object of class Collection that contains an item which is an array. You can access the array items in normal array syntax or using the object's getter.
$product->get('subscription'); //object oriented way
$product['subscription']; //access as an array item

Paginate json array in laravel

I'm currently using Laravel 5.6 and I have a result from an api. I'm trying to paginate the results and I'm not able to do it.
My json result is like this:
{#922 ▼
+"orders": array:50 [▼
0 => {#220 ▶}
1 => {#234 ▶}
2 => {#250 ▶}
3 => {#263 ▶}
4 => {#274 ▶}
5 => {#297 ▶}
6 => {#310 ▶}
7 => {#322 ▶}
8 => {#338 ▶}
9 => {#351 ▶}
]
}
I then get orders and put into a variable like so: $orders = $call->orders;
I have attempted this:
$orders = $shopifyData->paginate(20)->toArray();
I get this error:
Call to a member function paginate() on array
I have also attempted this: $orders::Paginate(20);
Also doesn't work.
I think I'm missing the first step to how to do this but honestly I'm lost. I'm not really sure how to go about it. Googling has several examples on how to do it when you are using an Eloquent model to retrieve the data from a database. It also shows how to do it when you query a database but nothing. The laravel documentation found under 5.6 pagination:
Paginating Query Builder Results
Paginating Eloquent Results
Manually Creating A Paginator
is very limited and only says to use paginator or lengthAwarePginator and to use array_slice.
Can someone point me in the right direction of how to achieve this?
I assume you are trying to paginate a plain-old PHP array in Laravel way.
The paginate function is only for query builders, so it doesn't work for arrays.
To do what you want, you first need to know at which page the user viewing. Usually, the current page is passed via the page GET parameter, but Laravel's LengthAwarePaginator offers functionality to extract that. You will need a use for this to work.
use Illuminate\Pagination\LengthAwarePaginator; // don't forget to add this
....
$current_page = LengthAwarePaginator::resolveCurrentPage();
Then you need to slice the array containing the result. Set the $perPage variable accordingly. Then you either need:
to turn your array into a Collection and slice it
$orders = $call->orders;
$orders_collection = new Collection($orders); // needs a use statement
$orders_collection = collect($orders); // alternative. You can use helper function
$current_page_orders = $orders_collection->slice(($current_page - 1) * $perPage, $perPage)->all(); // slice($offset, $number_of_item)
or to use array_slice directly for your array.
$orders = $call->orders;
$current_page_orders = array_slice($orders, ($current_page - 1) * $perPage, $perPage);
$current_page_orders is still a (sliced) Collection or array, so let's create a paginator instance.
$orders_to_show = new LengthAwarePaginator($current_page_orders, count($orders_collection), $perPage);
$orders_to_show is now the paginated result you want. You should be able to use it just like you handle paginated results from your database.

Laravel query different result between (identical?) two vs three argument 'where' clause

I'm having a very odd issue with a query in laravel (5.2) - I've got a collection created from some external source (an API), and I'm trying to run a 'where' query to extract specific records.
Originally, I was trying to extract all entries which were submitted during the current month (so, after the first day of this month)
$entries is the starting collection (time entries on a project - see end of post)
$thisMonthStart = (new Carbon('first day of this month'))->toDateString();
//value of this is 2017-02-01, and the issue is not resolved if I remove toDateString()
$entriesThisMonth = $entries->where('spent-at', '>', $thisMonthStart);
//returns an empty collection, but should have 15 results
Now the really odd part, is that I tried instead to get $entries where 'spent-at' is equal to the first day of the month - there should be one entry. If I don't explicitly specify the comparison operator, I get my expected result:
$entriesThisMonth = $entries->where('spent-at', $thisMonthStart);
//one $entries returned, see end of post
However if I specify the = operator
$entriesThisMonth = $entries->where('spent-at', '=', $thisMonthStart);
//empty collection returned
So I'm now very confused - presumably something is wrong in my original collection, but why does the specifying vs not specifying the operator make any difference? I would have thought that those two queries would give identical results?
(and obviously, not being able to specify the operator is not very helpful when trying to do a < or > comparison, but I'm mostly just interested in what the actual difference is between those two syntaxes, and so why they give different results?)
I couldn't find any info anywhere on how these two versions of the query work and so if it's expected that they could give different results - I would think that they should be identical, but maybe someone with a deeper understanding could explain what's causing this?
Thank you to anyone who can shed some light on the mystery!
A sample of the $entries collection in case is of any use (just a single record):
(NB there are definitely records from the current month, I know this example is too old)
Collection {#952 ▼
#items: array:367 [▼
175412141 => DayEntry {#958 ▼
#_root: "request"
#_convert: true
#_values: array:16 [ …16]
+"id": "175412141"
+"notes": ""
+"spent-at": "2013-10-03"
+"hours": "0.75"
+"user-id": "595841"
+"project-id": "4287629"
+"task-id": "2448666"
+"created-at": "2013-10-03T18:07:54Z"
+"updated-at": "2013-11-01T12:50:51Z"
+"adjustment-record": "false"
+"timer-started-at": ""
+"is-closed": "false"
+"is-billed": "true"
+"started-at": "10:45"
+"ended-at": "11:30"
+"invoice-id": "3633772"
}
And this is what is returned by the where query without the operator:
Collection {#954 ▼
#items: array:1 [▼
568944822 => DayEntry {#1310 ▼
#_root: "request"
#_convert: true
#_values: array:15 [▶]
+"id": "568944822"
+"notes": "Tweaking formatting on job ads and re shuffling ad order"
+"spent-at": "2017-02-01"
+"hours": "0.25"
+"user-id": "595841"
+"project-id": "4287629"
+"task-id": "2448666"
+"created-at": "2017-02-01T14:45:00Z"
+"updated-at": "2017-02-01T14:45:00Z"
+"adjustment-record": "false"
+"timer-started-at": ""
+"is-closed": "false"
+"is-billed": "false"
+"started-at": "14:30"
+"ended-at": "14:45"
}
]
}
To fix your issue... "returns an empty collection, but should have 15 results". If the collection already exists, you need to filter the results. Something like so:
$thisMonthStart = new Carbon('first day of this month');
$entriesThisMonth = $entries->filter(function ($entry) use ($thisMonthStart) {
return $entry['spent-at'] >= $thisMonthStart;
});
The method illuminate\Support\Collection::where is different to the database collection where, it doesn't take an operator as the second argument.
The where method signature to the collection object you are working with is where(string $key, mixed $value, bool $strict = true)
Your second example with the operator is looking for all elements in the collection that match the string '='.
For further reading on the collection you are working with (not an eloquent collection) look here
To get the 15 results that you are expecting, use the filter method on the collection.
Something along these lines should work:
$entriesThisMonth = $entries->filter (function ($e) use ($thisMonthStart) {
return $e ['spent-at'] > $thisMonthStart;
});

Resources