Laravel - Paginate function doesn't working on query building using IF - php

I am using paginate() on my Controller to pass data to the View. This is my index function using the paginate()
$userData = User::with('jobUnit')
->select('nip','name','address','phone','email','unit_id')
->paginate(10);
return view('users.index', [
'users' => $userData
]);
This is the result:
In the other function, I needed to add some IF conditions on the queries that is look like this:
$keyword = $request->keyword;
$searchedData = User::with('jobUnit')->select('nip','name','address','phone','email','unit_id');
if ($request->searchFilter == 'nip') {
$searchedData->where('nip','like','%'.$keyword.'%');
}
$searchedData->paginate(10);
The results is different, which is a problem for me because I am using the pagination links in the View. Here is the results:
Does the pagination() not working? Because I tried using the get() as well which should returns "Collection", but it was still returning the "Builder" results.

you need another variable to store the return data
$searchDataPaginated = $searchedData->paginate(10);
or using the current one if you want
$searchedData = $searchedData->paginate(10);

Related

Too few arguments for view error with laravel

I'm having a problem with laravel., I'm trying to send the variable $codes on my view :
$codes = Code::where('user', $id)->get();
return view('user.edit', ['user' => $user,'codes' => $codes]);
But I get that error Too few arguments to function e(), 0 passed in
The variable $user goes well but not the variable code, anyone have an idea for a solution?
Thank you all
use this:-
return view('user.edit')->with('codes',$codes);
you can get the user with :-
Auth::user()->name;
I'm pretty sure, if you are following Laravel naming conventions, in your eloquent query the column name is user_id and not user. Also if you are using such querys, and you have foreign, you can define relations in your models, like the following:
Code Model
public function user
{
$this->belongsTo(User::class);
}
User Model
public function codes
{
$this->hasMany(Code::class);
}
Instead of line
$codes = Code::where('user', $id)->get();
You can go with:
$codes = $user->codes();
If you don't have the foreigns in your database
$codes = Code::where('user_id', $id)->get();
If non of these helps, please dd() your variables before returning the view, and share result with me in comment. In laravel 7 how you return view is good.

Laravel edit pagination next and previous url for filtering

I am trying to create infinite scroll in laravel for that I am using default pagination and it is working fine but I want a pagination to use filtering.
public function infinite_scroll(Request $request)
{
$key = $request->input('key');
$group_name = $request->input('groupname');
$wachat = Wechat::where('key', '=', $key)->where('groupName', '=', $group_name)->orderBy('id', 'DESC')->paginate(2);
$this->response['values'] = $wachat;
$this->response['key'] = $key;
return response()->json(
$this->response
);
}
I am using this code and it is giving me this url in next url:
next_page_url: "http://localhost:8888/kc/kyo-webservice/public/api/v1/wechatinfinite?page=2"
But I want a filtering based on key and groupname for example when I pass a param groupname and key it should give me values.
When I am trying to get next page url it is not working I want my result for pagination based on my filter it should give me next page url like this:
next_page_url: "http://localhost:8888/kc/kyo-webservice/public/api/v1/wechatinfinite??key=smg1np1f77&groupname=group&page=2"
And it should give me result based on my filters.
used appends() pagination method here
Appending To Pagination Links
You may append to the query string of pagination links using the
appends method. For example, to append sort=votes to each pagination
link, you should make the following call to appends:
$wachat->appends(['key'=> $key,'groupname' => $group_name]);
in your controller do like that
public function infinite_scroll(Request $request)
{
$key = $request->input('key');
$group_name = $request->input('groupname');
$wachat = Wechat::where('key', '=', $key)->where('groupName', '=', $group_name)->orderBy('id', 'DESC')->paginate(2);
$wachat->appends(['key'=> $key,'groupname' => $group_name]);
$this->response['values'] = $wachat;
$this->response['key'] = $key;
return response()->json(
$this->response
);
}

Laravel Pagination with Get request

I've followed the instructions on the Laravel documentation for pagination with appends([]) however I'm having a little trouble with the persistence of these parameters.
Say for example, I pass home?category=Cars&make=Tesla to my view. What is the best way to paginate with them Get requests?
Right now I've passed the category as a parameter to the view as (where category is the model i've grabbed findOrFail with the request('category');)
$category_name = $category_model->name;
And then in my view it's like so:
{{ $vehicles->appends(['category' => $category_name])->links() }}
But when I go between pages in the pagination, this $category_name value doesn't seem to persist. Whats the recommended way to achieve what I want?
Thanks.
You can append the query string in your controller when you paginate the result. I'm not sure if that was your only question or even regarding applying the query string as a condition. So here is a sample showing you how to do both. This should give you an idea of how to do it. I just assumed the column names in this example.
$category = request('category');
$make = request('make');
$vehicles = Vehicle::when($category, function ($query) use ($category) {
return $query->where('category', $category);
})
->when($make, function ($query) use ($make) {
return $query->where('make', $make);
})
->paginate(10);
$vehicles->appends(request()->query());
return view('someview', compact('vehicles'));

Laravel 5.1 pagination groupby links rendering

I am on Laravel Framework version 5.1.45 (LTS).
One club can have many events. I am trying to list all the events, group them by year and show one page per year.
According to my Laravel version documentation "Currently, pagination operations that use a groupBy statement cannot be executed efficiently by Laravel. If you need to use a groupBy with a paginated result set, it is recommended that you query the database and create a paginator manually."
Here is my attempt to create the paginator manually and it seems to do the job:
public function index()
{
$page = Paginator::resolveCurrentPage() - 1;
$perPage = 1;
$events = new Paginator(Event::orderBy('date', 'desc')->groupBy(DB::raw('YEAR(date)'))->skip(($page - 1) * $perPage)->take($perPage + 1)->get(), $perPage, $page);
$events->setPath(['events/events']);
return view('events.index', ['events' => $events]);
}
And here is how I try to display the links at the bottom of the page.
{!! $events->render() !!}
If I remove the render bit, the page is displayed, albeit with no links. I can even go to the next page (year 2016) adding manually ?page=2 at the end of the url in my browser.
But if I leave the render bit in the index page, I get ErrorException in AbstractPaginator.php line 130: Array to string conversion.
What am I doing wrong?
Hope this snippet can help
public function index(Request $request)
{
$posts = Post::all()
->paginate($request->get('per_page', 25));
$grouped_by_date = $posts->mapToGroups(function ($post) {
return [$post->published_date => $post];
});
$posts_by_date = $posts->setCollection($grouped_by_date);
return view('posts.index', compact('posts_by_date'));
}
Basically redefine the collection with the grouped collection.

Passing a parameter to a custom find method in cakephp 3.x

I want to build a custom find function that retrieves bands for a given genre, i have tried this but the function can't access to the parameter $genre:
public function findGenre(Query $query, array $options)
{
$genre = $options['genre'];
$bands = $this->find()->contain([
'Genres' => function($q){
return $q->where(['Genres.id' => $genre]);
}
]);
return $bands;
}
I can access the $genre outside the contain() method, but not inside it.
My question is, how can i pass the $genre var to the function($q) inside the contain method.
I found where the problem is, i had to use the keyword use after the function($q), so that part of the code will look like this
$bands = $this->Bands->find()->contain('Genres', function($q) use ($genre){
return $q->where(['Genres.name'=>$genre]);
});
Also,the contain() method returns all the data even if the bands don't belong to a genre, but when i replaced it with matching() it worked just fine.
I hope this will help anyone who is having a similar problem in the future.
I was facing same issue but now it's resolved. I will explain you step by step:
My tables are:
articles: id,name,status,created
tags:id,name,status,created
articles_tags: id,article_id, tag_id
my query is this:
I want to pass my $tag_data['slug'] in matching variable but
directly this variable is not working in query. So I put in simple
$uses variable and now it's working properly.
$uses = $tag_data['slug'];
$contain_article = ['Tags'];
$query = $this->Articles->find('All')
->where(['Articles.status' => '1'])
->contain($contain_article)
->matching('Tags', function ($q) use ($uses) {
return $q->where(['Tags.slug' => $uses]);
});
Please try this :-)

Categories