Laravel Manual Pagination Error - php

I have a issue related to Laravel5 Manual Pagination.
I need to process an array of query builder result and some other arrays and make a pagination for that.
controller.
public function searchCategory($id){
$arr = DB::table('business_businesscatagories')->lists('fk_business_id');
return Paginator::make($arr, count($arr), 2);
}
Namespaces..
use Illuminate\Pagination\LengthAwarePaginator as Paginator;
But I got the error like below..
FatalErrorException in IndexController.php line 122:
Call to undefined method Illuminate\Pagination\LengthAwarePaginator::make()
How can I solve this issue....

I examined Illuminate\Pagination\LengthAwarePaginator and was able to confirm that it doesn't have make method.
However you can achieve this by using its constructor method.
__construct(mixed $items, int $perPage, int|null $currentPage = null, array $options = array())
Since you already have the correct namespace specified:
use Illuminate\Pagination\LengthAwarePaginator as Paginator;
You could simply do this:
$paginator = new Paginator($items, $total, $per_page);

Related

laravel - pagination on collection

Im trying to work on eloquent collection. Got User model and Article model with relation one to many. One User can have many Articles. One Article belongs to one User.
This is how I retrieve articles written by a specifield user in a controller:
public function articles(User $user) {
if(empty($user)) $user = Auth::user();
$articles = $user->articles->paginate(10); //here comes collection
// passing results to view
return view('articles.index', compact('articles'))
->with('i', (request()->input('page', 1) - 1) * 10);
}
I found many solutions for paginating results that are a collection. The on I like the most is here: https://stackoverflow.com/a/56142421/14330487
My code is same. Using laravel 9, php 8.1.3 right now on a new project. I've created Collection::macro in AppServiceProvider boot() method.
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Collection;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
// builtin bootstrap views for pagination
Paginator::useBootstrapFive();
/**
* Paginate collection
*
* #param int $perPage
* #param int $total
* #param int $page
* #param string $pageName
* #return array
*/
Collection::macro('paginate', function ($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,
]
);
});
}
}
Dont know why my VSC shows me that forPage() and count() methods are undefined...
I dont get any errors running my app. But also cant see any results.
Routing, controller and view is fine, when Im doing it another way it shows results, but the way I get it is a crap. Using Collection::macro is far more gentle.
I have in my AppServiceProvider.php file lines like use Illuminate\Support\Collection and LengthAwarePaginator.
Really dont know why it doesnt work. Maybe its laravel 9 fault? Solution I found looks like made for laravel 8.
Thanks for help.
I've done that another way, without AppServiceProvider, but just by creating a Helper class. Solution found here: https://sam-ngu.medium.com/laravel-how-to-paginate-collection-8cb4b281bc55
My first attepmt did not work cause of method articles argument default value declaration. Should looks like:
public function articles(User $user = null) {}
and not known definition of forPage() and count() method are just display errors from VSC.
Both solutions works fine.
Just considering now which attempt is better.
Use this function
firstItem()
lastItem()
total()
links()
Example
#Controller
$orders = DB::table('orders')->paginate(15);
#View
$orders->firstItem();
$orders->lastItem();
$orders->total();
$orders->links();

symfony doctrine-> findBy(), Can I return a parsable PHP array without using the repository method?

If I use this method to retrieve data I cannot parse it in my PHP like this $data[0]['string']. PHP just says this is an Object and it cannot parse it as Array
error message
Cannot use object of type App\Entity\MyEntity as array
Controller code:
$data = $this->em
->getRepository(Myclass::class)
->findBy(['foo' => $var]);
How can I return a parsable array from a simple findBy() directly from the controller without having to go through the Repository and QueryBuilder with ->getArrayResult() ?
All you need to do is to create your custom function in your repository:
public function findItByFoo($var){
$qb = $this->createQueryBuilder('myClass');
$qb->select("myClass")
->where('foo = :var')
->setParameter('var', $var);
$result = $qb->getQuery()->getArrayResult();
return $result;
}
You cannot achieve this with built-in findBy method. More specifically, the findBy definition is:
$repository->findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null);
As you can see for yourself there is not any argument for the hydration mode.
Finally, since you want to hydrate your entities as arrays instead of objects, and you want to do that in your controller, the only solution is something like this:
$data = $this->em->getRepository(Myclass::class)->createQueryBuilder('m')
->select("m")->where('foo = :var')->setParameter('var', $var)
->getQuery()->getArrayResult();
As you can see, it almost identical with the code in the findItByFoo() function I wrote above, I just wanted to mark that you can do that also in your controller (even not suggested, programmatically speaking).

Call to a member function paginate() on array in Laravel

Here is my code in laravel,
use Illuminate\Pagination\LengthAwarePaginator;
$result = DB::connection('mysql')->select("select * from login_master")->paginate(5);
Its showing Call to a member function paginate() on array. How to user paginate() in this code.
Try this:
DB::connection('mysql')->table("login_master")->paginate(5);
If using Eloquent:
LoginMaster::paginate(5);

Non-static method Illuminate\Support\Collection::where() should not be called statically

I try to get the data array as following:
$coupons = $user->coupons::where('is_activated_flg', 1)->where('is_used_flg', 0)->lists('amount');
I have this error:
Non-static method Illuminate\Support\Collection::where() should not be called statically
Could you tell me what the problem is?
You might want to change it into something like this:
$couponQuery = $user->coupons()->where('is_activated_flg', 1)->where('is_used_flg', 0);
$couponCollection = $couponQuery->get();
..or combined:
$coupons = $user->coupons()->where('is_activated_flg', 1)->where('is_used_flg', 0)->get();
If you are using Laravel 5.1 or slightly below you might want to consider using pluck instead of lists:
https://laravel.com/docs/5.1/collections#method-pluck
$plucked = $collection->pluck('name');
$plucked->all();
Try to send an array of where clauses
from official docs
$users = DB::table('users')->where([
['status','1'],
['subscribed','<>','1'],
])->get();
https://laravel.com/docs/5.2/queries#selects
I'd probably define an eloquent relationship in my user model.
/**
* User can have many coupons
*/
public function coupons()
{
return $this->hasMany('App\Coupons')->where('is_activated_flg', 1)->where('is_used_flg', 0);
}
and then call it like
$user = User::findOrFail($id);
$coupons = $user->coupons;

YII: Call to a member function offset() on a non-object

I am very new to php and yii2, i am trying to read all data records by active record
The code below give error Call to a member function offset() on a non-object
$cmylist = ClassInfo::find()->all();
$pages = new Pagination(['totalCount' => count($cmylist)]);
$models = $cmylist->offset($pages->offset)->limit($pages->limit)->all();
Seems cmylist is a array and i can not call offset and count on it
This is really made me crazy, thanks for your help
Of course, if You call all() it's create final result. Call ->offset() before ->all()
just see
http://www.yiiframework.com/doc-2.0/yii-data-pagination.html
Calling all() returns array of result models, You need to adjust Your code this way:
$cmylist = ClassInfo::find(); //activeQuery instance
$pages = new Pagination(['totalCount' => $cmylist->count()]);
$models = $cmylist->offset($pages->offset)->limit($pages->limit)->all();

Categories