Pagination pages problem collection / array - php

I've used the query builder instead of the normal select(I had to, I have added pagination).
query builder example :
$dataGlobal = DB::table('articles')
->orderBy('articleDate', 'desc')
->orderBy('articleHour', 'desc')
->orderBy('articleMinute', 'asc')
->orderBy('articleSeconde', 'asc')
->limit(150)
->paginate(15);
With this code, normally I shoud have 10 pages no more, but instead of the 10 pages I have 23. Counting from page 5 to 23, all of these pages aren't working with this error code; Undefined array key 0
For the pagination I'm using the bootstrap 5 blade pagination (vendor folder)
My question is why am I having all of theese pages ? The weird thing is I have this problem in one page only which is my home page, but in the other ones I don't have this problem at all everything is good
Maybe I didn't give enought details let me know if you guys need me to add something.

Actually, you can't use limit with pagination.
see this answer: Using limit parameter in paginate function

Related

Eager loading with constraints generates too many queries. How can I alleviate that?

I have 4 tables that are related in the database and in models as follows:
Users (hasMany(communities), hasMany(comments), hasMany(submissions))
Communities (belongsTo(user), hasMany(submissions))
Submissions (belongsTo(community), belongsTo(user), hasMany(comments))
Comments (belongsTo(user) , belongsTo(submission))
Now. If I use the relations to get, say the 25 latest submissions, like this:
$submissions = Submission::simplePaginate(25);
I'm met with 76 queries run, after using foreach to loop through the results.
If I use eager loading with the following
$submissions = Submission::with(['user', 'community', 'comments'])->simplePaginate(25);
I'm met with 4 queries which is optimal (I think).
Now, my problem is that, on communities, I have a database field called active which accepts a 1 for an active community, and a 0 for an inactive. As you might have guessed, the previous query returns everything, including inactive communities.
I thought about eager loading constraints, so I used the following:
$submissions = Submission::with([
'community' => function($query) {
$query->active();
}
]
)->with(['user', 'comments'])->simplePaginate(25);
This still does that job with 4 queries, but now I run into another problem. This method filters the inactive communities, but still loads the posts, users and comments. And now I'm left with a result where I get posts from inactive communities.
Finally, I tried, upon reading this community, the following:
$submissions = Submission::whereHas(
'community', function($query) {
$query->active();
}
)->with(['user', 'comments'])->simplePaginate(20);
So, instead of using ->with() I used ->whereHas() as someone suggested. However, while this produces the correct results, i.e. it gives me posts, comments and users from the active communities only, it now does that in 23 queries, as per the feedback I get from Laravel Debugbar.
Is this normal? Is this the only way I can do this through Eloquent and without writing custom queries with joins? Am I blowing 23 queries out of proportion?
Any help would be greatly appreciated.
Your problem is that the active() scope is running a query for every community you are retrieving, in your case 20.
To optimize this you could make a specific relation in the Submission model where you filter the active communities proactively.
// Submission model
public function activeCommunities (){
return $this->hasMany(Community::class)->whereActive(true);
}
Now your query would look like:
$submissions = Submission::with(['user', 'comments', 'activeCommunities])
->simplePaginate(25);
This should perform 4 queries I believe.
Hope this helps you.
So, after tinkering with it for a while, I found a solution, but I'm still not sure. I'm posting this for future reference, since it solved my problem. The code I used is the following
$submissions = Submission::whereHas(
'community', function($query) {
$query->where('is_active', true);
}
)->with(['user', 'community'])->withCount('comments')
->paginate(25);
So, I tried using whereHas() to check for the models existence before actually eager loading the community model, if that makes sense? It seems to get me the results I want, since I now execute a total of 4 queries to get all the submissions, and the related info, filtering the inactive communities.

Laravel 5.2 Display each users posts they've made this week as count

I'm trying to display a list of all the users and how many posts they've each made this week, and how many they've made last week, inside of a form
I've used a hasMany relation between the two tables and the relationship it's self is working.
return $this->hasMany('App\applications', 'user_id');
inside of the view what I have that's displaying the post count is
{{$user->applications->count()}}
The main thing I'm stuck on is the SQL Query or using Carbon inside of the controller function to achieve this.
If anyone has done this before your help would be greatly appreciated!
Thank you.
Since you want to count posts for many users, eager load the data and use withCount():
User::withCount(['applications' => function($q) {
$q->whereBetween('created_at', [Carbon::now()->startOfWeek(), Carbon::now()]);
}])->get();
If you want to count the number of results from a relationship without actually loading them you may use the withCount method, which will place a {relation}_count column on your resulting models.
https://laravel.com/docs/5.4/eloquent-relationships#counting-related-models

Display unique node using views in drupal

I am trying to display latest articles using views module. There are 12 article should be displayed per click of pagination excluding the duplicate entry. So, I tried as:
checked Advanced > Query settings > Distinct but no luck.
I have also tried as Views Distinct Settings > Filter/Aggregate this field > Filter Repeat, it works but number of articles are displayed less than 12.
Then, I tried to do it using the hook mymodule_views_query_alter but I do not understand how can I accomplish this task. I tried as:
if($view->current_display == "latest_article"){
$query->add_groupby('node.title');
}
But no solution. How can I override the query and inject DISTINCT function to get unique record.
Did you tried using Use aggregation option from Advanced section ? Hope this helps.

Wrong pagination link count laravel

I need to skip the first n records, say 5 from a table and paginate the rest of it. The following is the code that i am using.
$skipNewsListArr = array(1,2,3,4,5);
$wrongPaginationLinks = DB::table('news')
->whereNotIn('news_id',$skipNewsListArr)
->orderBy('news_date','desc')
->paginate(5);
But the above code outputs the pagination links corresponding to the whole table. How can i achieve pagination by skipping records based on some condition.

PHP & MySQL Join

I'm relatively new to coding in general, first year CS student and all of that. I'm using PHP to display a list of school classes categories and a list of assignment posts within each category. The desired output would be something like this:
CATEGORY 1
-Assign Post 1
-Assign Post 2
CATEGORY 2
-Assign Post 0
Using join gives me partial functionality, because it gets all the assign posts, but when I loop through and post the data it posts the Category title more than once. I then tried using group_by but it's only posting one post per category.
I'm not gonna post all my code, simply the db queries. I'll happily post the other code if you think the problem may be there.
//Select our classes, and get assignments from each class
$this->db->select('*');
$this->db->from('categories');
$this->db->join('assignments', 'categories.cat_id = assignments.assign_cat_id');
$this->db->group_by("cat_id");
//Return the classes and assignments in an array
$query = $this->db->get();
return $query->result_array();
Not to tricky right? Any help is of course appreciated :).
UPDATE
I have figured out that group_concat will post the assignment names, and then I can explode the results. Is this the only way, or is there a way to get it to post in a nice friendly array. The only reason I ask is I feel this adds un-necessary code in my view file, where I'm exploding the data.
Thank you!
Dont use group by ...use sort by Category id and while showing/or preparing array of data you can club records as per category..you cant achive this by single SQL

Categories