skip to Main Content

How do I generate pagination links?
My code looks like this:

// In Model
public function comments()
{
  return $this->hasMany(Comment::class);
}

// In Controller
public function show(User $user)
{
  $user = User::query()
   ->with(['comments' => fn ($query) => $query->paginate(20)->withQueryString()])
   ->find($user->id);

  return view('user.show', [
   'user' => $user,
  ]);
}

// In blade
@foreach ($user->comments as $comment)
//more
@endforeach

{{ $user->comments->links() }}  // not working!

2

Answers


  1. public function show(User $user), followed by $user = User::find($user->id) is completely redundant… You already have $user, and even with the additional stuff, this is still silly; just use $user->load(...) in the future.

    But, since you’re trying to Paginate comments, just do like so:

    public function show(User $user) {
      $comments = $user->comments()->paginate(20);
      return view('user.show', [
       'user' => $user,
       'comments' => $comments
      ]);
    }
    

    Then in your view:

    @foreach ($comments as $comment)
      <!-- ... -->
    @endforeach
    
    {{ $comments->links() }} 
    
    Login or Signup to reply.
  2. FOLLOW THIS STEP

    1.OPEN YOUR PROJECT

    2.Go to Providers

    3.Open AppServiceProviders

    4.Paste This Code

     public function boot()
        {
            //
            Paginator::useBootstrap();
        }
    

    Or This Is The Whole Code Of AppServiceProvider

    <?php
    
    namespace AppProviders;
    
    use IlluminateSupportServiceProvider;
    use IlluminatePaginationPaginator;
    
    
    class AppServiceProvider extends ServiceProvider
    {
        /**
         * Register any application services.
         *
         * @return void
         */
        public function register()
        {
            //
        }
    
        /**
         * Bootstrap any application services.
         *
         * @return void
         */
        public function boot()
        {
            //
            Paginator::useBootstrap();
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search