Laravel 5.5 Paginate the Query - Eager Loading - laravel

I have a problem and can't figure out how to solve it. I've searched online but still couldn't get a firm answer. What I'm trying to do is to paginate Inquiries table - or the query below. Everything seems to work (at least I'm getting 20 inquiries per page, however I can't figure out how to display the links()?
I'm saving Inquiries in the $thecusts collection and passing it to the view.
Tables and relations : Employees - Dealers (manytomany)
Dealers-customers(1 to many)
Customers-inquiries (1 to many).
So I need to paginate x Inquiries for the employee that has many dealers.
Anyone can help ?
$justch = $me->employeehasdealers()->get(['dealers.dealer_id','dealer','abbreviation']); //list of dealers assigned to auth employee
$justch2=$justch->load(['DealerHasInquiries'=>function($query){
$query->with('inquiriescomments:comments_inquiries_id,inquiry_id,employee_id,comments','inquiryspdl','inquiriescustomers:customer_id,customer')->paginate(20);
}]);
$thecusts = new Collection();
foreach ($justch2 as $just) {
$thecusts = $thecusts->merge($just->DealerHasInquiries);
}

The problem is you're not passing back the paginator instance. You can manually create one in your controller based on $thecusts:
$perPage=20;
return view('my-view', ['paginator' => new Paginator($thecusts->toArray(), $perPage)]);
Then you can call the links method on the paginator instance in your view:
{{ $paginator->links() }}
Edit
You may be able to simply all this though in a single query like:
$thecusts = $me->employeehasdealers()->with(['DealerHasInquiries'=>function($query){
$query->with('inquiriescomments:comments_inquiries_id,inquiry_id,employee_id,comments','inquiryspdl','inquiriescustomers:customer_id,customer');
}])->paginate(20);
return view('my-view, compact('thecusts'));

however I can't figure out how to display the links()?
You can do this in your blade:
{{ $justch2->links() }}

The Answer has been posted by btl - (Much appreciate it!)
Here is my code with some additions:
Controller:
$perpage=19;
$justch = $me->employeehasdealers()->with(['DealerHasInquiries'=>function($query) use ($perpage){
$query->with('inquiriescomments:comments_inquiries_id,inquiry_id,employee_id,comments','inquiryspdl','inquiriescustomers:customer_id,customer')->simplePaginate($perpage);
}])->get(['dealers.dealer_id','dealer','abbreviation']);
foreach ($justch as $just) {
$thecusts = $thecusts->merge($just->DealerHasInquiries);
}
$paginator = new Paginator($thecusts->toArray(),$perpage, Paginator::resolveCurrentPage(),['path'=>Paginator::resolveCurrentPath()]);
$inquiries = $thecusts;
return view('/inquiries', ['paginator'=>$paginator,'inquiries' => $inquiries]);
Blade: {{$paginator->links()}}

Related

Laravel eloquent query with sum of related table

I have a table users and posts with columns user_id and post_views.
In post_views I keep information how many times post was display.
And now, in query I would like to get user with sum of post_views all his posts.
I tried do something like this:
User::where(['id'=>$id])->with('posts')->get();
And in model I defined:
public function posts()
{
return $this->hasMany('App\Models\Post')->sum('post_views','AS','totalViews');
}
But without success.
How to do it?
Thank you
You can use a modified withCount():
public function posts()
{
return $this->hasMany('App\Models\Post');
}
$user = User::withCount(['posts as post_views' => function($query) {
$query->select(DB::raw('sum(post_views)'));
}])->find($id);
// $user->post_views
You can use
User::withCount('posts')->find($id)
to get the user with the id $id and a posts_count attribute in the response
I'm not fully sure what the intention of ->sum('game_plays','AS','totalVies'); is - you would need to add more context if you want this
Just something to add with regards to your shown code: No need to query by id using where + the get() at the end will make you query for a collection. If you want to get a single result use find when searching by id
As always laravel has a method for that : withSum (Since Laravel v8)
Note : I know that at the time of the message was posted, the method did not exist, but since I came across this page when I was looking for the same result, I though it might be interesting to share.
https://laravel.com/docs/9.x/eloquent-relationships#other-aggregate-functions
In your case it should be :
$user = User::withSum('posts as total_views', 'post_views')->find($id);
Then you can access to the result :
$user->total_views

Join in laravel 5.5 [duplicate]

This question already has answers here:
Laravel eloquent counting a relation
(3 answers)
Closed 5 years ago.
I am trying to make a query where I get the number of comments on a News in a row in laravel.
News Table
News_Comments Table
Display count of comments in 'Kommentare'
This is the query in mysql.
SELECT news.Id,news.title,news.body,news.created_at, COUNT(news_comments.id) AS Kommentare
FROM news
LEFT JOIN news_comments ON news_comments.fk_news_id = news.id
GROUP BY news.id
Result of this query
How would I write that in laravel 5.5?
Thank you very much!
You have to set the relationship between News and NewsComments.
In News Model, supposing that news_comments is in NewsComment Model, in App folder. Set the relationship:
public function newsComments()
{
return $this->hasMany('App\NewsComment', 'fk_news_id');
}
And then, to get the count, you can use count() method:
$count = $news->newsComments()->count();
Or, directly using blade:
{{ $news->newsComments()->count() }}
Make a model for news table name News and another for comments table name Comment. And then in your News model, define a hasMany() relationship method like -
public function comments(){
return $this->hasMany(Comment::class);
}
And then in your controller, retrieve like this-
$newses = News::with('comments')->get();
This will load all news with corresponding all comments. If you want to load single news with all comments then -
$news = News::with('comments')->where('id',$news_id)->first();
To get the comment count, you can count() on relationship like -
$count = News::find($news_id)->comments()->count();

Pagination and a Where clause

I there, im using eloquent to create a query where gets the galleries from a specific user_id, but i want also to implement the pagination, but is not working the way im doing.
ex:
$galleries = Gallery::paginate(10)->where('user_id', $userId)
->get();
$galleries = Gallery::where('user_id', $userId)->paginate(10);
In the controller you are supposed to do :
$galleries = Gallery::where('user_id', $userId)->paginate(10);
In the view use :
{{ $galleries->appends(Input::except('page'))->links() }}

Laravel OrderBy comments in posts

I have post and comments tables where of course comments belongs to posts.
I want to sort posts now with eloquent by amount of comments.
How can i do that in laravel?
I tried to order by date using:
Post::orderBy('created_at', 'DESC')->paginate(6);
i want the same but sorting by comments with are on other database but they are connected in model.
EDIT:
I end up now having this query:
$post = Post::
join('comments', 'comments.post_id' , '=', 'posts.id')
->groupBy('posts.id')
->orderBy(DB::raw('COUNT(posts.id)'))
->paginate(6);
{{ $post->author }} works...
but i cant get for example {{ $post->comment->count()}} from blade. In my previous query (above) it works. dunno why.
This answer makes help.
You should be able to use the Collection's sortBy() and count() methods to do this fairly easily.
$hackathons = Hackathon::with('participants')->get()->sortBy(function($hackathon)
{
return $hackathon->participants->count();
});

Laravel Eloquent with and find

Why is this not working?
Article::with('category')->find($ids)
I got a Array to String Conversion Exception.
But if i split the query into 2 parts like this:
$articles = Article::with('category')
and
$articles = $articles->find($ids)
I didn't get any exception and the result is right.
Just for the posterity... other way you can do this is:
Article::with('category')->whereIn('id', $ids)->get();
This should be faster because it's leaving the query to the database manager
Try:
Article::with('category')->get()->find($ids);
You need to get the articles first before you can call find() I believe.
Warning: This retrieves every single article from the database and loads them all into memory, and then selects just one from all that data and returns it. That is probably not how you would want to handle this problem.
This will give you the results based on an array of IDs in Laravel 4
Article::whereIn('id', $ids)->with('category')->get();
Create object and set his properties with relationships
for example, code in your Controller or Service
$article = new Article;
$article = $article->find($id);
$result->article = $article;
$result->article->category = $article->category;
return response()->json($result);
Code in your Model
public function category() {
return $this->hasOne('App\Category');
}

Resources