Laravel cache::remember is returing object as an array - caching

Laravel Cache::remember is returning a LengthAwarePaginator object as an array.
function getNotifications( $userID ) {
$values = Cache::remember('cache-key', 10, function() {
$query = DB::table( 'user_notifications' )
->leftJoin( 'notifications', 'user_notifications.notification_id', '=', 'notifications.id' )
->where( 'user_notifications.user_id', $userID )
->select( 'notifications.*' )
->orderBy('created_at', 'DESC')
->paginate(5);
return $query;
});
return $values;
}
If I dd($query) before returning from Cache closure, it's returning the following object, that accepts $value->links() to display pagination.
But whenever the Cache is storing $query into $values it's returning values as an array:
I tried commenting out the unserialize-block:
/*foreach( $values as $key => $value ) :
$values[$key]->meta = self::maybeUnserialize($value->meta);
endforeach;*/
and confirmed that, that's not the cause.
I also tried, but failed:
$values = collect($values);
With multiple check and cross-check I am confirming that, the issue is the Cache::remember.
How can I force the Cache::remember return things as it is? So that I can let $object->links() work for me.
The actual code can be found here.

The issue is, Cache is made to store data, not the instance. So there are two ways to do this:
When caching, cache information per page, or
Get all the data while fetching, but make your own pagination
Solution 1:
We went for the second. But in case you need to go for the first solution, here's the code, I got from Laracasts, provided by chrisml:
$statuses = Cache::remember("statuses_{$id}_page_{$page}", 3, function() use ($event, $sort) {
return $event->statuses()
->with('comments')
->latest()
->paginate(10);
});
On the above code, the cache key is changing on every page, so the cache is storing per page.
Solution 2:
But for my case, we thought we should go for the second, and that would be wise for us, in our case. So, we've to make our own pagination. My luck that psampaz did the base for us on their blog:
Custom data pagination with Laravel 5 — by psampaz
So, instead of using ->paginate() we're fetching all the data first, and caching them as previous.
$values = Cache::remember('cache-key', 10, function() {
$query = DB::table( 'user_notifications' )
->leftJoin( 'notifications', 'user_notifications.notification_id', '=', 'notifications.id' )
->where( 'user_notifications.user_id', $userID )
->select( 'notifications.*' )
->orderBy('created_at', 'DESC')
->get(); // <----------- here
return $query;
});
But before returning the $values, we're making our own pagination. We made some fixes to the psampaz's code:
use Illuminate\Support\Collection;
use Illuminate\Pagination\LengthAwarePaginator;
function getNotifications( $userID ) {
// Collapsed the cached values here :)
$values = Cache::remember('cache-key', 10, function() {...});
// Get current page form url e.g. &page=6.
$currentPage = LengthAwarePaginator::resolveCurrentPage();
// Get current path.
$currentPath = LengthAwarePaginator::resolveCurrentPath();
// Create a new Laravel collection from the array data.
$collection = new Collection($values);
// Define how many items we want to be visible on each page.
$perPage = 5;
// Slice the collection to get the items to display on the current page.
$results = $collection->slice(($currentPage - 1) * $perPage, $perPage)->all();
// Create our paginator and pass it to the view.
$values = new LengthAwarePaginator($results, count($collection), $perPage, $currentPage, ['path' => $currentPath]);
return $values;
}
And finally, we can easily use the $object->links() for pagination, and it's awesome! :)

Related

Cache eloquent model with all of it's relations then convert it back to model with relations?

I am trying to optimize a project that is working pretty slow using caching. I'm facing a problem that I don't quite understand how to cache full eloquent models with their relationships and later on covert them back to a model with all relations intact. Here's a fragment of my code
if (Cache::has($website->id.'_main_page')) {
$properties = (array) json_decode(Cache::get($website->id.'_main_page'));
$page = Page::hydrate($properties);
}else{
$expiresAt = now()->addMinutes(60);
$page = Page::with(['sections', 'pageSections.sectionObjects'])->where('website_id', $website->id)->where('main', 1)->first();
Cache::put($website->id.'_main_page', $page->toJson(), $expiresAt);
}
Problem is, hydrate seems to be casting this data as a collection when in fact it's suppose to be a single model. And thus later on I am unable to access any of it's properties without getting errors that they don't exists. $properties variable looks perfect and I would use that but I need laravel to understand it as a Page model instead of stdClass, I also need all of the relationships to be cast into their appropriate models. Is this even possible? Any help is much appreciated
Is there any reason you can't use the cache like this
$page = Cache::remember($website->id.'_main_page', 60 * 60, function () use ($website) {
return Page::with(['sections', 'pageSections.sectionObjects'])
->where('website_id', $website->id)
->where('main', 1)
->first();
});
Conditional
$query = Page::query();
$key = $website->id.'_main_page';
if (true) {
$query = $query->where('condition', true);
$key = $key . '_condition_true';
}
$query::with(['sections', 'pageSections.sectionObjects'])
->where('main', 1)
$page = Cache::remember($key, 60 * 60, function () use ($query) {
return $query->first();
});

How to paginate a collection and query builder in laravel

I have +30K items in my requests table so i decided to back-end paginate the page showing the requests to user. The problem is that every user does not have permission to see all the requests and it's based on a lot of factors which i made a function that returns whether the user have permission to see a request or not.
The problem is in requests in process i have to pass every request in process to the function to get the permission ( processing request is a small set of items ). So i used the filter function on processing requests and it gives me a collection of 10 items. Now i want to merge the big set of items which is closed requests that can be +10K items with the processing ones and use the paginate feature.
How can i do that ?
This function will explain more what am trying to say :
public function getRequests(){
$closedRequests = request::join('request_logs', 'request_logs.request_id', '=', 'requests.id')
->select("requests.id", "requests.user_id", "requests.form_type", "requests.created_at", "requests.request_status")
->whereNotIn('request_status', [-2, 0])
->where('request_logs.user_id', Auth::user()->id);
$processingRequests = request::select("requests.id", "requests.user_id", "requests.form_type", "requests.created_at", "requests.request_status")
->where('request_status', 0)
->get()
->filter(function ($request) {
return FormsController::checkUserPermissionToConsultForm($request, true);
});
$closedRequests = $closedRequests->union($processingRequests)
->orderBy('created_at', 'desc')
->paginate(5);
return $closedRequests;
}
The function above is what i tried to do but it generate an error saying
Call to a member function getBindings() on array
You can create a collection and push the items to it, then use then create a class
<?php
namespace App\Support;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection as BaseCollection;
class Collection extends BaseCollection
{
public function paginate($perPage, $total = null, $page = null, $pageName = 'page')
{
$page = $page ?: LengthAwarePaginator::resolveCurrentPage($pageName);
return new LengthAwarePaginator(
$this->forPage($page, $perPage),
$total ?: $this->count(),
$perPage,
$page,
[
'path' => LengthAwarePaginator::resolveCurrentPath(),
'pageName' => $pageName,
]
);
}
}
Then you can call it like this
use App\Support\Collection;
$items = [];
$collection = (new Collection($items))->paginate(20);
This solution is from a gist I found on github. you can see it here

laravel more than one result from single query

I am trying to get all rows and distinct column from single query. but paginate method is only giving result but not pagination option like total prev next etc..
$offers = Offer::whereHas('users', function ($q) use ($authUser) {
$q->where('user_id', $authUser->parent_id);
$q->where('publisher_id', '=', $authUser->id);
});
and distinct column
$websites = $offers->distinct()->get(['website']);
with pivot columns (just wanted to show my full query)
$offers->orderBy($sortBy, $orderBy)->paginate($perPage)->map(function ($offer) {
if (!empty($offer->users)) {
$manager = $publisher = '';
foreach ($offer->users as $user) {
$manager = $user->pivot->user_id;
$publisher = $user->pivot->publisher_id;
}
$offer->manager = $manager;
$offer->publisher = $publisher;
}
return $offer;
});
Return
return response()->json([
'offers' => $offers,
'websites' => $websites
], 200);
hope my question will make sense.
Thanks.
You should run getCollection() before mapping to get the paginator's underlying collection.
(https://laravel.com/api/7.x/Illuminate/Pagination/LengthAwarePaginator.html#method_getCollection)
$offers->orderBy($sortBy, $orderBy)->paginate($perPage)
->getCollection()
->map(function ($offer) {
// ...
return $offer;
});
I'm answering based on it being $offers:
Your usage of map() is copying the modified results of your paginate() call to a new collection and that collection does not include the pagination information. That's why you no longer have pagination information.
Since there result of paginate() is already a usable collection, you can use each() instead of map() which will alter the objects in-place.

Laravel alternative to paginate on collection?

On my website, I have Submissions, and submissions can have comments.
Comments can have upvotes and downvotes, leading to a total "score" for the comment.
In this example, before passing the comments to the view, I sort them by score.
$comments = Comment::where('submission_id', $submission->id)->where('parent_id', NULL)->get();
$comments = $comments->sortByDesc(function($comment){
return count($comment['upvotes']) - count($comment['downvotes']);
});
This works fine. The higher the score of a comment, the higher it is sorted.
However, I want to paginate these results.
If I do ->paginate(10) instead get(), the following sortByDesc will only sort those 10 results.
So logically I would want to add the paginator after the sortByDesc like so:
$comments = $comments->sortByDesc(function($comment){
return count($comment['upvotes']) - count($comment['downvotes']);
})->paginate(10);
However this will return the error:
Method Illuminate\Database\Eloquent\Collection::paginate does not
exist.
as expected.
My question is, what is the alternative to using paginate in this situation?
EDIT:
When trying the response of #party-ring (and switching the double quotes and single quotes) I get the following error:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an
error in your SQL syntax; check the manual that corresponds to your
MariaDB server version for the right syntax to use near '["upvotes"])
- count($comment["downvotes"]) desc limit 10 offset 0' at line 1 (SQL: select * from comments where submission_id = 1 and parent_id is
null order by count($comment["upvotes"]) -
count($comment["downvotes"]) desc limit 10 offset 0)
You are trying to paginate after the get, the solution i try on my website is this and it works
$users = User::where('votes', '>', 100)->get();
$page = Input::get('page', 1); // Get the ?page=1 from the url
$perPage = 15; // Number of items per page
$offset = ($page * $perPage) - $perPage;
return new LengthAwarePaginator(
array_slice($users->toArray(), $offset, $perPage, true), // Only grab the items we need
count($users), // Total items
$perPage, // Items per page
$page, // Current page
['path' => $request->url(), 'query' => $request->query()] // We need this so we can keep all old query parameters from the url
);
You could add a macro:
if (!Collection::hasMacro('paginate')) {
Collection::macro('paginate', function ($perPage = 25, $page = null, $options = []) {
$options['path'] = $options['path'] ?? request()->path();
$page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
return new LengthAwarePaginator(
$this->forPage($page, $perPage)->values(),
$this->count(),
$perPage,
$page,
$options
);
});
}
Then you can use a collection to paginate your items:
collect([1,2,3,4,5,6,7,8,9,10])->paginate(5);
See Extending Collections under Introduction
Give this a try:
$comments = Comment::where('submission_id', $submission->id)
->where('parent_id', NULL)
->orderBy(DB::raw("count($comment['upvotes']) - count($comment['downvotes'])"), 'desc')
->paginate(10);`
SortBy returns a Collection, whereas you can only call paginate on an instance of QueryBuilder. OrderBy should return an instance of QueryBuilder, and you should be able to do the subtraction using a DB::raw statement.
** edit
I have just read about orderByRaw, which might be useful in this scenario:
$comments = Comment::where('submission_id', $submission->id)
->where('parent_id', NULL)
->orderByRaw('(upvotes - downvotes) desc')
->paginate(10);`
You might have to play around a bit with your subtraction above as I don't know the structure of your comments table.
A couple of links which might be useful:
laravel orderByRaw() on the query builder
https://laraveldaily.com/know-orderbyraw-eloquent/

Laravel simplePaginate() for Grouped Data

I have the following query.
$projects = Project::orderBy('created_at', 'desc');
$data['sorted'] = $projects->groupBy(function ($project) {
return Carbon::parse($project->created_at)->format('Y-m-d');
})->simplePaginate(5);
When I try to paginate with the simplePaginate() method I get this error.
stripos() expects parameter 1 to be string, object given
How can I paginate grouped data in this case?
The created_at attribute is already casted as a Carbon Object (by default in laravel models). that's why you are getting that error. Try this:
$projects = Project::orderBy('created_at', 'desc')->get();
$data['sorted'] = $projects->groupBy(function ($project) {
return $project->created_at->format('Y-m-d');
})->simplePaginate(5);
this answer is just for the error you're getting. now if you want help with the QueryBuilder, can you provide an example of the results you're expecting to have and an example of the database structure ?
The pagination methods should be called on queries instead of collection.
You could try:
$projects = Project::orderBy('created_at', 'desc');
$data['sorted'] = $projects->groupBy('created_at');
The problem was solved. I was create custom paginator via this example:
https://stackoverflow.com/a/30014621/6405083
$page = $request->has('page') ? $request->input('page') : 1; // Use ?page=x if given, otherwise start at 1
$numPerPage = 15; // Number of results per page
$count = Project::count(); // Get the total number of entries you'll be paging through
// Get the actual items
$projects = Project::orderBy('created_at', 'desc')
->take($numPerPage)->offset(($page-1)*$numPerPage)->get()->groupBy(function($project) {
return $project->created_at->format('Y-m-d');
});
$data['sorted'] = new Paginator($projects, $count, $numPerPage, $page, ['path' => $request->url(), 'query' => $request->query()]);
simplePaginate Method is exist in the path below:
Illuminate\Database\Eloquent\Builder.php::simplePaginate()

Resources