I have LengthAwarePaginator in variable dataTypeContent, when I use where he do query only on first page. But I need on all pages and return new filtered items by where.
$dataTypeContent->where('category_id', 48);
LengthAwarePaginator {#303 ▼
#total: 283
#lastPage: 19
#items: Collection {#1 ▶}
#perPage: 15
#currentPage: 1
#path: "/admin/products"
#query: []
#fragment: null
#pageName: "page"
}
More code: https://github.com/the-control-group/voyager/blob/1.1/src/Http/Controllers/VoyagerBaseController.php
How I can do where on all pages?
I see your variable $dataTypeContent = $someQuery->paginate();
You should use where before paginate(). $dataTypeContent = $someQuery->where()->paginate();
Related
so I’m running this query when a user selects multiple categories on the frontend of the site, I want it to bring back the products that are related to the selected categories… this works, however, I have 2 collections that I need to merge together. Here is the code:
$category = Category::whereIn('permalink', $request->get('categoryFilter'))->with('products')->get()->pluck('products');
I get the following back:
Illuminate\Support\Collection {#1779 ▼
#items: array:2 [▼
0 => Illuminate\Database\Eloquent\Collection {#1780 ▼
#items: []
#escapeWhenCastingToString: false
}
1 => Illuminate\Database\Eloquent\Collection {#1799 ▼
#items: array:24 [▶]
#escapeWhenCastingToString: false
}
]
#escapeWhenCastingToString: false
}
The first category has no products but the second has, is there a way of merging these 2 together?
Try this,
$category = Products::whereIn('category_id',Category::whereIn('permalink',
$request->get('categoryFilter')
)->pluck('id')
)->get();
I need to add pagination, but it seems complicated in my case, because I get data from database with paginate, but then I modify this data and when I call links() method on the blade, I get the following exception
Method Illuminate\Support\Collection::links does not exist.
My code in the Controller method:
$transactionsByLastMonth = Transaction::where('created_at', '>=', Carbon::now()->subDays(30)->toDateTimeString())
->where('user_id', Auth::user()->id)
->with(['user', 'propertyFrom', 'propertyTo', 'paddockFrom', 'paddockTo', 'cattleTypeFrom', 'cattleTypeTo'])
->paginate(10);
$transactionsByDays = collect(TransactionResource::collection($transactionsByLastMonth))
->sortByDesc('created_at')
->groupBy(function($date) {
return Carbon::parse($date['created_at'])->format('d');
});
return view('user.reports.index', compact('transactionsByDays'));
Yes, a pagination limits my data to 10 rows, but due to I'm grouping data by days, my collection modifies itself and I can't use $transactionsByDays->links() method to show pagination.
If see dd($transactionsByDays) , it looks like:
Illuminate\Support\Collection {#1381 ▼
#items: array:3 [▼
"01" => Illuminate\Support\Collection {#1019 ▼
#items: array:7 [▼
0 => array:16 [▶]
1 => array:16 [▶]
2 => array:16 [▶]
3 => array:16 [▶]
4 => array:16 [▶]
5 => array:16 [▶]
6 => array:16 [▶]
]
}
31 => Illuminate\Support\Collection {#1386 ▼
#items: array:2 [▼
0 => array:16 [▶]
1 => array:16 [▶]
]
}
30 => Illuminate\Support\Collection {#1384 ▼
#items: array:1 [▼
0 => array:16 [▶]
]
}
]
}
Therefore I need to paginate all arrays together which inside "01", 31, 30...
How can I do it?
Maybe rewrite code above in the controller somehow?
The main aim is that I need to group data to every day according to my json-resource class.
Any ideas?
I've found a solution gyus. I had to pass also a variable transactionsByLastMonth and use links() method over this.
In the meantime I use foreach on the my blade file over transactionsByDays variable. It's correctly works together cause it uses the same data from database, just in the first case its not filtered and not grouped and in the second one it is.
return view('user.reports.index', compact('transactionsByLastMonth', 'transactionsByDays'));
Pagination is returning blank on next page. The result gets found but lost when I go to next page. This is query in my controller
if($request->has('SearchBtn')){
$search = $request->input('Search');
$query = \App\User::join('suppliers', 'users.id' ,'=', 'suppliers.user_id')
->where('company', 'LIKE', "%{$search}%")
->paginate(1);
if($query->isEmpty()){
$query = \App\Keywords::join('users', 'users.id' ,'=', 'keywords.user_id')
->join('suppliers', 'users.id' ,'=', 'suppliers.user_id')
->where('Keyword', 'LIKE', "%{$search}%")
->paginate(1);
}
return view('/Buyers/SearchResult', compact('query'));
}
And this is dd($query)
Illuminate\Pagination\LengthAwarePaginator {#1238 ▼
#total: 2
#lastPage: 2
#items: Illuminate\Database\Eloquent\Collection {#1233 ▶}
#perPage: 1
#currentPage: 1
#path: "http://localhost:8000/Buyers/SearchResult"
#query: []
#fragment: null
#pageName: "page"
+onEachSide: 3
#options: array:2 [▶]
}
As you can see it finds pages but can show only first one. My guess is that it has something to do with join because queries without it work just fine with paginate(). I honestly don't know what to try or how to start debugging this. If I switch paginate() with get() everything is fine and the data is shown correctly.
This is dd($request)
Illuminate\Http\Request {#43 ▼
#json: null
#convertedFiles: []
#userResolver: Closure($guard = null) {#246 ▶}
#routeResolver: Closure() {#255 ▶}
+attributes: Symfony\Component\HttpFoundation\ParameterBag {#45 ▶}
+request: Symfony\Component\HttpFoundation\InputBag {#51 ▶}
+query: Symfony\Component\HttpFoundation\InputBag {#51 ▶}
+server: Symfony\Component\HttpFoundation\ServerBag {#47 ▶}
+files: Symfony\Component\HttpFoundation\FileBag {#48 ▶}
+cookies: Symfony\Component\HttpFoundation\InputBag {#46 ▶}
+headers: Symfony\Component\HttpFoundation\HeaderBag {#49 ▶}
#content: null
#languages: null
#charsets: null
#encodings: null
#acceptableContentTypes: null
#pathInfo: "/Buyers/SearchResult"
#requestUri: "/Buyers/SearchResult?_token=RG7LzXrHaL4x2jHOoCHC3TLbUqs22XaJDjuulOCo&Search=company&SearchBtn="
#baseUrl: ""
#basePath: null
#method: "GET"
#format: null
#session: Illuminate\Session\Store {#269 ▶}
#locale: null
#defaultLocale: "en"
-preferredFormat: null
-isHostValid: true
-isForwardedValid: true
-isSafeContentPreferred: null
basePath: ""
format: "html"
}
UPDATE 1.0:
The blank page was returned due to this statement if($request->has('SearchBtn')) however now I face a new problem when I search something I get correct number of pages and when I got to the next page page count goes up and it shows all the results from the database.
UPDATE 1.1
And I fixed that by appending search to the query like this
$query = \App\User::join('suppliers', 'users.id' ,'=', 'suppliers.user_id')
->where('company', 'LIKE', "%{$search}%")
->paginate(1)->appends(['Search'=>$search]);
I have a $location collection that looks like this:
Collection {#225 ▼
#items: array:5 [▼
0 => GoogleAddress {#336 ▼
-id: "ChIJjWwHAP72w0cR44_HJ-bRcJE"
-locationType: "ROOFTOP"
-resultType: array:1 [▶]
-formattedAddress: ""
-streetAddress: null
-intersection: null
-political: ""
-colloquialArea: null
-ward: null
-neighborhood: null
-premise: null
-subpremise: null
-naturalFeature: null
-airport: null
-park: null
-pointOfInterest: null
-establishment: null
-subLocalityLevels: AdminLevelCollection {#339 ▶}
-coordinates: Coordinates {#331 ▶}
-bounds: Bounds {#332 ▶}
-streetNumber: "21"
-streetName: ""
-subLocality: null
-locality: ""
-postalCode: ""
-adminLevels: AdminLevelCollection {#337 ▶}
-country: Country {#335 ▶}
-timezone: null
-providedBy: "google_maps"
}
1 => GoogleAddress {#344 ▶}
2 => GoogleAddress {#352 ▶}
3 => GoogleAddress {#360 ▶}
4 => GoogleAddress {#368 ▶}
]
}
So I am trying to get the formattedAddress like this:
$location[0]->formattedAddress
But I get the following error:
Cannot access private property
Geocoder\Provider\GoogleMaps\Model\GoogleAddress::$formattedAddress
Anyone can help me out here?
It's a collection Do it like this
$location->first()->formattedAddress
The variable is private, meaning you can only access it from within the same class. In this case, the class has a getter method called getFormattedAddress() you can use.
Source: https://github.com/geocoder-php/Geocoder/blob/master/src/Provider/GoogleMaps/Model/GoogleAddress.php#L182
Solution: $location->first()->getFormattedAddress()
And a bit of advice, if you don't understand the private part, you really should have a look at the PHP documentation on visibility: http://php.net/manual/en/language.oop5.visibility.php
First, try to get the first object with $model->first()
If not, try to use mutators:(Here an example)
public function getNameAttribute()
{
return $this->attributes['firstName'];
}
This is the result of dd($followers):
LengthAwarePaginator {#401 ▼
#total: 144
#lastPage: 8
#items: Collection {#402 ▼
#items: array:18 [▶]
}
#perPage: 20
#currentPage: 1
#path: "http://myurl.com/SocialCenter/public/twitterprofile/JZarif"
#query: []
#fragment: null
#pageName: "page"
}
Now I want to know, how can I overwrite #total? I mean I want to reinitialize it to 18. So this is the expected result:
LengthAwarePaginator {#401 ▼
#total: 18
#lastPage: 8
#items: Collection {#402 ▼
#items: array:18 [▶]
}
#perPage: 20
#currentPage: 1
#path: "http://myurl.com/SocialCenter/public/twitterprofile/JZarif"
#query: []
#fragment: null
#pageName: "page"
}
Is doing that possible?
Noted that none of these work:
$followers->total = 18;
$followers['total'] = 18;
You could use reflection:
$reflection = new \ReflectionObject($followers);
$property = $reflection->getProperty('total');
$property->setAccessible(true);
$property->setValue(
$followers,
18
);
For reference, see:
http://php.net/manual/en/class.reflectionobject.php
http://php.net/manual/en/class.reflectionproperty.php
You should make a getter and setter function.
But you can use PHP-Reflections. Like this example:
<?php
class LengthAwarePaginator
{
private $total = true;
}
$class = new ReflectionClass("LengthAwarePaginator");
$total = $class->getProperty('total');
$total->setAccessible(true);
$total->setValue(18);