Pagination and a Where clause - laravel

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() }}

Related

Laravel whereHas

I have the following eloquent query that has two withs but wants the query more specific.
So far I have:
$club_models = \App\Models\Clubs\Club::whereActive(1)
->with('group_ex_pro_id')
->with('campaigns')->get();
I'd like it to be the below but am getting an error:
$club_models = \App\Models\Clubs\Club::whereActive(1)
->with('group_ex_pro_id')
->with('campaigns')->whereHas('new-campaign-name')->get();
I ultimately want it to include campaigns but want it to be where campaigns have the specific new-campaign-name name
I don't think you need both with and whereHas together. Assuming the campaign name you'd like the campaigns to be is stored in $campaignName, try this:
$club_models = \App\Models\Clubs\Club::whereActive(1)
->with('group_ex_pro_id')
->whereHas('campaigns', function (Builder $query) use ($campaignName) {
$query->where('new-campaign-name', $campaignName);
})->get();

Laravel How to easy filtering of Eloquent all?

I have a Customer Model that it`s called like this:
$Customer = Customer::all();
How can I change if I have a filter request like "status"?
I tried this way:
$Customer = Customer::orderBy('id');
if($filter->has('active')){
$Customer->where('status',$filter->status);
}
$Customer->count();
The problem is if I don`t set any filter I don't get all Customers. And I don't want to write another if. I want to change
$Customer = Customer::orderBy('id');
to get all and if filter is set I want only filter. How to do this?
when you get the query() method of the eloquent model, you obtain a query builder for that model, all what you have to do is add wheres and orderby... to that query builder then call count() to get the count:
$customer = Customer::query()->orderBy('id');
if($filter->has('active')){
$customer= $customer->where('status',$filter->status);
}
$customerCount=$customer->count();

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

Laravel 5.5 Paginate the Query - Eager Loading

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()}}

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();
});

Resources