Search code examples
phplaravellaravel-5.7

Laravel pagination {{$users->links}} doesnt exist


I have set a view composer whit view share that give User data to the sidebar when i try to paginnate it while using

User::paginate(1)

and put $users->links into the blade it says links is not found but when I use

User::all()

It works and give no erros back but i can not paginate the table i dont see where the error is coming from. this is the error display:

Call to undefined method App\User::links() (View: C:\Users\kaasv\medialab\resources\views\layouts\sidebar.blade.php) (View: C:\Users\kaasv\medialab\resources\views\layouts\sidebar.blade.php) (View: C:\Users\kaasv\medialab\resources\views\layouts\sidebar.blade.php)

AppServiceProvider

   use Illuminate\Support\ServiceProvider;
   use Illuminate\Support\Facades\Schema;
   //use Illuminate\View\View;
   use View;
   //use App\Repositories\UserRepository;

   use App\User;

  class AppServiceProvider extends ServiceProvider
{
/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    Schema::defaultStringLength(191);

    View::share('user', User::paginate(1));

}

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

the sidebar.blade.php

    <h1>Alle Studenten</h1>

  @if (Auth::check())


<table class="table">
    <tr>
        <th scope="col">#</th>
        <th scope="col">Name</th>
        <th scope="col">Student Number</th>
    </tr>
    @foreach($user as $users)

        <tr>
            <th scope="row">
               {{$users->id}}
            </th>
            <th>
                <a class="text-dark" href="/admin/leerling/{{ $users->id }}">
                    {{$users->name}}
                </a>
            </th>
            <th>
                {{$users->student_number}}
            </th>
        </tr>

    @endforeach

</table>

{{ $users->links() }}

     @endif

Solution

  • First of all I don't suggest using Laravel's View Composers because they will be initialized on every view, even the ones you add with @include, @extends, etc. Which might lead to big performance hit if the data you are sharing from the Composers is pulled from the Database.

    Second of all, paginate() method accepts number of results to return as it's parameter, which would mean by returning only 1 user will resolve to Paginator instance which in fact has method you are looking for: links(), but the issue is you're naming it user where you are accessing users inside the view