I'm trying to wrap my head around pagination based on what I've read.
I've never done pagination before so excuse my lack of knowledge. Based on the documentation, I do not see how to get the next page's data. I'm using a client-side (js) library.
Backend Model:
return User::where('col', $value)->paginate(15);
The above gave me this json.
Based on the data available: from, last_page etc, what should I pass to the backend to get, say, page 2? From the json I can get page 2 but how to query for page 2? Something like this would make sense:
return User::where('col', $value)->paginate(15)->nextPage(2);
My understanding of paginate is so show the amount of items per page.
Doing this in raw sql is doable:
LIMIT 10 OFFSET 15
To elaborate, here's my controller:
public function all()
{
$customers = ( new Customer )->getCustomers();
if ($customers) {
return response()->json($customers, 200);
}
return response()->json([], 200);
}
You can paginate resources using laravels default pagination inputs.
You don't have to do ->nextPage() or something just send page input and laravel will handle rest of it.
like this;
http://example.com/posts?page=2;
I aggree, Laravel Pagination Docs is not beginner friendly.
Hi you could configure like this:
$users = Users::all()->paginate(5);
return view('users.index',compact('users'))
->with('i', (request()->input('page', 1) - 1) * 5);
This will return 5 records per page. Configure by your needs.
In you index file, do something like:
<table class="table table-bordered">
<tr>
<th>no</th>
<th>user id</th>
<th>Name</th>
</tr>
#foreach ($users as $user)
<tr>
<td>{{ ++$i }}</td>
<td>{{ $user->user_id }}</td>
<td>{{ $user->name }}</td>
#endforeach
</table>
{!! $users->links() !!}
Related
i’m looking for a solution to a problem that I’m having for a while now. Maybe you can inspire me to do this better. I’m trying not to make a basic mistake in the planning process therefore I’m asking you for advice.
I’m having a Contact::model which has few fixed attributes like id etc. Additionally I would like to have different attributes created dynamically for the whole Contact::model. Some user will be given the functionality to add attributes like name, email, address to the whole model. I’ve dropped the idea of programmatically updating the table itself by creating/dropping columns (this would introduce different problems). As for now i've created two additional tables. One with the additional column names [Columns::model] and a pivot table to assign the value to a Contact::model and Column::model.
To list all contacts i’m preparing the ContactColumn table as array where the first key is the contact_id and the second is the column_id, therefore i get the value. This introduces the n+1 issue. This would not be that bad, but with this approach it will be extremely hard (or resource consuming) to order the contacts by dynamic column values, filtering, searching etc.
Can you somehow guide me to a better solution. How can i merge the contact collection with the values for given columns so it looks like it was a fixed table?
<table>
<thead>
<tr>
<th>Fixed columns [i.e. ID]</th>
#foreach ($columns as $column)
<th>{{ $column->name }}</th>
#endforeach
</tr>
</thead>
<tbody>
#foreach ($contacts as $contact)
<tr>
<td>{{ $contact->id }}</td>
#foreach ($columns as $column)
<td>
#if (array_key_exists($column->id, $values[$contact->id]))
{{ $values[$contact->id][$column->id] }}
#endif
</td>
#endforeach
</tr>
#endforeach
</tbody>
</table>
And the $value array.
foreach (ColumnContact::all() as $pivot) {
$values[$pivot->contact_id][$pivot->column_id] = $pivot->value;
}
return $values;
Edit: I've solved it like this
$this->contacts = Contact::when($this->dynamicColumnName, function($query) {
$query->join('column_contact', function ($join) {
$join->on('id', '=', 'column_contact.contact_id')
->where('column_contact.column_id', '=', $this->dynamicColumnName->id);
})
->orderBy('value', $this->orderingDirection);
})
(...)
->paginate(self::PER_PAGE);
Apart from the fixed fields, add an extra JSON field in your schema called 'custom_fields'. Have a look into => https://github.com/stancl/virtualcolumn
Separate table for custom fields is not a good idea because then you have to handle model events separately and so on.
I have added Datatables in my application and i wanted to make the ID of each entry to be a hyperlink to the edit page in order for a user to be able to edit their Post. But i am getting a 404 Not Found error
I tried updating my route file but i don't get the correct result and i cannot figure what i am doing wrong
My web php file has:
Route::get('edit','PostsController#edit');
The index for my posts is
<table class="display" id="postsTable">
<thead>
<tr>
<td>ID</td>
<th>Title</th>
<th>Slug</th>
<th>Subtitle</th>
<th>Content</th>
<th>Category</th>
</tr>
</thead>
<tbody>
#foreach($posts as $post)
<tr>
<td>{{$post->id}}</td>
<td>{{$post->title}}</td>
<td>{{$post->slug}}</td>
<td>{{$post->subtitle}}</td>
<td>{{$post->content}}</td>
<td>{{$post->category_id}}</td>
</tr>
#endforeach
</tbody>
And the PostsController edit function is:
public function edit($id)
{
$posts = Post::findOrFail($id);
return view('posts.edit',compact('posts'));
}
I tried searching online and playing a bit with my routes but i managed to make things worse rather than solving my issue. any help is much appreciated!
You can set Route name like below
Route::get('edit/{id}','PostsController#edit')->name('edit_post');
Then in HTML section use it like below
<tbody>
#foreach($posts as $post)
<tr>
<td>Edit Post</td>
<td>{{$post->title}}</td>
<td>{{$post->slug}}</td>
<td>{{$post->subtitle}}</td>
<td>{{$post->content}}</td>
<td>{{$post->category_id}}</td>
</tr>
#endforeach
</tbody>
You should add some validation on client side to be sure that you have data so you can add your code inside if condition like below
#if ($posts ?? count($posts) ?? false)
// Your code here
#endif
Are you sure there is a record in your database that matches the $id that came with the get method? If there is no matching record, findOrFail($id) returns 404 pages.
In your controller check, the posts are found or not
public function edit($id)
{
$posts = Post::findOrFail($id);
// check post are found or not
if(!isset($posts)){
# show your errors if data not found
}
return view('posts.edit',compact('posts'));
}
As I am developing a project in larawel 5.3. and I am using two tables in database first users ans second points you can see my points table structure in this link.
I want to get user id in laravel 5.3 controller with Auth::user()->id but it creates error their
So when a transection occurs. it is saved in points table getting assousiated with user_id so net points of a user can can be taken as using folloing query
$points = Points::select(DB::raw("sum(p_add)-sum(p_less) as Total"))->where('user_id', Auth::user()->id)->first();
now I am goin to gett all data of users in a single admin page. so I am using following code in controller
public function users_list()
{
$ptitle = "Website Users";
$pdesc = "";
$total_users = User::count();
$users = User::select('*')->orderby('created_at', 'desc')->get();
return view('admin.all-users-list',
['ptitle' => $ptitle,
'pdesc' => $pdesc,
'users' => $users,
'total_users' => $total_users,
]);
}
And folloing foreach loop to fetch users data in view page
<table class="table table-hover">
<tbody><tr>
<th>ID</th>
<th>User Name</th>
<th>Email</th>
<th>Country</th>
<th>Date</th>
<th>Points</th>
</tr>
<?php foreach ( $users as $u ){ ?>
<tr>
<td>{{ $u->id }}</td>
<td>{{ $u->user_name }}</td>
<td>{{ $u->email }}</td>
<td>{{ $u->country }}</td>
<td>{{ $u->created_at }}</td>
<td>????</td>
</tr>
<?php }?>
</tbody></table>
and result on view is as in this image
now I dont now that how can I fetch net points from points table for every user. please provide me some help to solve this issue.
you can make public function and call it every loop in foreach loop. Or create static function on the Points model class to get points for every user by using user_id as argument.
Put getUserPoints on Points model class
public static function getUserPoints($userId){
$points = self::select(DB::raw("sum(p_add)-sum(p_less) as Total"))
->where('user_id', $userId)->first();
if( $points != null ){
return $points->Total;
}
return 0;
}
}
And you can call it every loop as {{ \App\Points::getUserPoints($u->id) }}
I am trying to implement pagination in laravel and got following error
Undefined property: Illuminate\Pagination\LengthAwarePaginator::$name
Here is my controller function
public function showTags($id)
{
$tag = Tag::find($id)->paginate(5);
// when lazy loading
$tag->load(['posts' => function ($q) {
$q->orderBy('id', 'desc');
}]);
return view('blog.showtags')->withTag($tag);
}
Here is the Tag Model
class Tag extends Model
{
public function posts()
{
return $this->belongsToMany('App\Post');
}
}
The Tag and Post model has belongsToMany Relationship so there are many posts under the specific tag and my aim is to iterate all posts under the specific tags descending order of post and also to implement pagination in that page.
Here is the code for showtags view
<table class="table">
<thead>
<tr>
<th>#</th>
<th>Title</th>
<th>Tags</th>
</tr>
</thead>
<tbody>
<?php $count = 1; ?>
#foreach($tag->posts as $post)
<tr>
<th>{{ $count++ }}</th>
<th>{{ $post->title }}</th>
<th>#foreach($post->tags as $tag)
<span class="label label-default">{{ $tag->name }}</span>
#endforeach
</th>
</tr>
#endforeach
</tbody>
</table>
//Here is the code i used for pagination in view
<div class="text-center">
{!! $tag->posts->links() !!}
</div>
If anybody know how to do this please respond. Thanks in advance.
I solve the problem by using a simple trick. My aim was to paginate all posts under the same tags just like you guys can see in StackOverflow.
The modified controller function is
public function showTags($id)
{
$tag = Tag::find($id);
// when lazy loading
$tag->load(['posts' => function ($q) {
$q->orderBy('id', 'desc')->paginate(10);
}]);
return view('blog.showtags')->withTag($tag);
}
As you guys see that I move the paginate() function from find to load function which I use before for sorting post by descending order.
Now in view instead of using traditional method {!! $tag->links() !!} for making link of pagination
I use {!! $tag->paginate(10) !!}
With this line $tag = Tag::find($id)->paginate(5); You should get only one tag(or null if tag with your id dose not exist), and after that you want paginate it. If you want paginate your tags get all tags and after that paginate it Tag::paginate(5)
I am using a hasMany in my Model class to retrive the clients notes, how ever i want to order these notes by the latest date created in laravel blade template.
My code is below and im getting an error on this.
Please advice me..
#foreach($clients->notes->orderBy('created_at', 'desc') as $note)
<table class="table table-bordered">
<tr>
<td class="col-xs-2 col-md-2"><b>Created On:</b> {{ date('d/m/y', strtotime($note->created_at)) }} <b>#</b> {{ date('g:i A', strtotime($note->created_at)) }} </td>
<td class="col-xs-14 col-md-12">{{ $note->notes }}</td>
</tr>
</table>
#endforeach
Guessing, because you haven't told us what error you're getting, but:
$clients->notes is an already-fetched collection of results. $clients->notes() is a query builder that you can apply further logic like ordering or additional criteria to.
You likely want:
$clients->notes()->orderBy('created_at', 'desc')->get()
but you should do that in the controller and pass it to the view instead of having the query directly in the Blade template.
(You can alternatively use Laravel's collection functions on $clients->notes, including the sortBy() function).
Data must be ordered within controller or models. If you have used hasMany validation in model you can do as mentioned below
In model write association
public function notes()
{
return $this->hasMany('Note')->orderBy('created_at', 'desc');
}
In your controller function associate client with notes like this
$clients = Client::with('notes')->get();
Hope you get your answer