Laravel Collection paginate does not exist - laravel

I'm trying to implement basic pagination when retrieving notifications, but I get the following error.
Method
Illuminate\Notifications\DatabaseNotificationCollection::paginate does
not exist.
public function index()
{
$messages = collect();
$notifications = auth()->user()->unreadNotifications->paginate(5);
foreach ($notifications as $notification) {
$message = NotificationToMessageFactory::make($notification->type)
->toMessage($notification->data);
$messages->push($message);
}
}

You've to call paginate() on query builder instance not on a collection.
Correct syntax will be :
$notifications = auth()->user()->unreadNotifications()->paginate(5);

You should paginate before looping through the collection, otherwise you will be retrieving all records matching the query, when you only need 5. Like this:
$messages = collect();
$notifications = auth()->user()->unreadNotifications()->paginate(5);
foreach($notifications as $notification) {
$message = NotificationToMessageFactory::make($notification->type)->toMessage($notification->data);
$messages->push($message);
}

Related

Getting error on applying pagination on collection in laravel

Getting error on applying pagination on collection in laravel -> Method Illuminate\Support\Collection::paginate does not exist.
public static function search_query($query)
{
$users = Searchy::search('snippets')->fields('snippets_name',
'seo_description','snippets_description','snippet_tags')->query($query)
->getQuery()->get();
$collection = (new Collection($users))->paginate(20);
return $collection;
}
you can try like this:
$users = Searchy::search('snippets')->fields('snippets_name',
'seo_description','snippets_description','snippet_tags')->query($query)
->getQuery()->paginate(20);
$collection = (new Collection($users))->response()->getData(true);
get() method on builder is returning collection. Suggesting to use paginate on builder to get the Paginator instance. Try with below code if that solves your problem. Refer more in docs
public static function search_query($query) {
//create a builder for your query.
$users = Searchy::search('snippets')
->fields('snippets_name',
'seo_description',
'snippets_description',
'snippet_tags')
->query($query)
->getQuery();
$collection = $user->paginate(20);
return $collection;
}

Laravel 6: trying to get property of non-object

Error: Trying to get property 'gender_id' of non-object
Controller:
public function printreports(Request $request)
{
$id = $request->get('select2'); //eg. id=1
$teachers = DB::table('teachers')->find($id);
return view('teachers.report1',compact('teachers'));
}
View:
#foreach($teachers as $teacher)
{{$teacher->gender_id}}
#endforeach
while if i do it with Eloquent by replacing following query it works, but i want to do it with DB query as stated above.
$teachers = Teacher::find($id);
you need use where, and after it you will have collection.
$teachers = DB::table('teachers')->where('id', $id)->get();
when you use find, you have single item
You don't need to use foreach while you use find().
#if(sizeof($teachers))
{{$teachers->gender_id}}
{{$teachers->gender_id}}//whatever field you need to display
{{$teachers->gender_id}}//whatever field you need to display
#endif
If you use get(),
$teachers = DB::table('teachers')->where('id','=',$id)->get();
#if(sizeof($teachers))
#foreach($teachers as $teacher)
{{$teacher->gender_id}}
{{$teacher->gender_id}}//whatever field you need to display
{{$teacher->gender_id}}//whatever field you need to display
#endforeach
#endif
$teachers = DB::table('teachers')->find($id); will return a single Model or  null, try using $teachers = DB::table('teachers')->get();
If you want to return collection to view then use get() method like this:-
public function printreports(Request $request)
{
$id = $request->get('select2');
$teachers = DB::table('teachers')->where('id', $id)->get();
return view('teachers.report1',compact('teachers'));
}

How to use transform in paginated collection in laravel

I want to use map or transform in paginated collection in laravel 5.5 but I am struggling it work
This is what I was trying to do but getCollection is not available in LengthAwarePaginator as what we used to do in previous laravel versions see: How to transform paginated collection
$query = User::filter($request->all()
->with('applications');
$users = $query->paginate(config('app.defaults.pageSize'))
->transform(function ($user, $key) {
$user['picture'] = $user->avatar;
return $user;
});
This is what I receive but there is no pagination details in my result
How can I return transformed collection with pagination details?
For Laraval >= 8.x: if you want to perform the transform() on the collection of the paginated query builder result instead of doing the pagination on the full collection, one can use the method through():
User::filter($request->all()
->with('applications')
->paginate(config('app.defaults.pageSize'))
// through() will call transform() on the $items in the pagination object
->through(function ($user, $key) {
$user['picture'] = $user->avatar;
return $user;
});
I have ended up building custom paginate function in AppServiceProvider
use Illuminate\Support\Collection;
In register of AppServiceProvider
Collection::macro('paginate', function ($perPage, $total = null, $page = null, $pageName = 'page') {
$page = $page ?: \Illuminate\Pagination\LengthAwarePaginator::resolveCurrentPage($pageName);
return new \Illuminate\Pagination\LengthAwarePaginator(
$this->forPage($page, $perPage),
$total ?: $this->count(),
$perPage,
$page,
[
'path' => \Illuminate\Pagination\LengthAwarePaginator::resolveCurrentPath(),
'pageName' => $pageName,
]
);
});
You should paginate before retrieving the collection and transforming as follows:
$query = User::filter($request->all())->with('applications')->paginate(50);
$users = $query->getCollection()->transform(function ($user, $key) {
//your code here
});
dd($users);
It should give you your desired result.
Your problem is that you are printing the $users variable that hold the array of the users in the current page. To get the paginated list try to return/print $query instead.
So your code should be as following:
$query = User::filter($request->all()
->with('applications');
$users = $query->paginate(config('app.defaults.pageSize'))
->transform(function ($user, $key) {
$user['picture'] = $user->avatar;
return $user;
});
return response()->json($query);
Happy Coding!
You can use method setCollection from Paginator class:
https://laravel.com/api/8.x/Illuminate/Pagination/Paginator.html#method_setCollection
$messages = $chat->messages()->paginate(15);
$messages->setCollection($messages->getCollection()->transform(function($item){
$item->created = $item->created_at->formatLocalized('%d %B %Y %H:%M');
return $item;
}));

Sorting collections in Laravel

I've got a little problem with my Laravel controller and sorting it:
public function index()
{
$achievements = Achievement::all();
$news = News::all();
$livingspaces = Livingspace::all();
$therapies = Therapy::all();
$events = Event::all();
$collection = collect();
foreach ($achievements as $achievement) {
$collection->push($achievement);
}
foreach ($news as $new) {
$collection->push($new);
}
foreach ($livingspaces as $livingspace) {
$collection->push($livingspace);
}
foreach ($events as $event) {
$collection->push($event);
}
foreach ($therapies as $therapy) {
$collection->push($therapy);
}
$sortedData = $collection->sortBy('category')->sortByDesc('created_at');
return response()->json([
'sortedData' => $sortedData
], 200);
}
It's not sorting at all. It should sort if after the data in the created_at timestamp which comes out of the box when creating a new migration for a Laravel controller. But I can't sort the data. I think it has something to do with pushing the data from the DB directly into the collection and it's not looking for "created_at" at all. It's not giving any errors or anything its just not doing anything. The same goes for sortBy.
sortByDesc method has the same signature as the sortBy method, but will sort the collection in the opposite order. By default sortBy to do the ascending operation. If you want to sort by decending:
$sortedData = $collection->sortBy('category', true);

How to Get Data From Model in Function With Laravel

Is it possible to get data from the model in a function? I want to get the SupplierID data from the Product model.
public function productAjax($id)
{
$product = new Producttext();
$products = $product->productexts($id);
$hitung_products = $products->count();
$suplierproduct = Company::select('id', 'CompanyName')
->where(['id' => $products->SupplierID])
->first();
}
However, on execution, I get the following error.
Property [SupplierID] does not exist on this collection instance.
If you have producttext ID then
$product = Producttext::find($id)
OR
$product = Producttext::where('id',$id)->first();
//test and check that you have it $product->SupplierID
$suplierproduct = Company::select('id', 'CompanyName')->where('id',$product->SupplierID)
->first();
You should try this:
public function productajax($id)
{
$products = Producttext::where('id',$id)->first();
$suplierproduct = Company::select('id', 'CompanyName')
->where(['id' => $products->SupplierID])
->first();
}

Resources