Home > Enterprise >  Pagination links not working on user profile in Laravel
Pagination links not working on user profile in Laravel

Time:01-18

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!

CodePudding user response:

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

CodePudding user response:

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 App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Pagination\Paginator;


class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
        Paginator::useBootstrap();
    }
}
  • Related