0
votes

I wanted to create pagination in index page and as I read in Laravel documentation it is possible to use paginate method with orderBy method when I do that I faced error:"Method Illuminate\Database\Eloquent\Collection::orderBy does not exist.". The code I am using:

public function index()
    {
        $user_id=auth()->user()->id;
        $user=User::find($user_id);
        $personal=$user->personalAccounting->orderBy('asc')->paginate(2);
        $balance=$user->balance;
        return view('personal.index', compact('personal','balance'));

    }  


 @extends('layouts.app')
    @section('content')
    <h1>Домашняя Бухгалтерия</h1>
    <br>
    @if($balance==0)
    <h2 class="text-center">Ваш Баланс: <span class="badge badge-primary">0.00</span></h2>
    @elseif($balance<0)
    <h3 class="text-center">Ваш Баланс: <span class="badge badge-danger">{{$balance}}</span></h3>
    @else
    <h3 class="text-center">Ваш Баланс: <span class="badge badge-success">+{{$balance}}</span></h3>
    @endif
    <br>
    <a href="/personal/create" class="btn btn-primary">Создать</a>
    <br>
    @if(count($personal)>0)
    @foreach($personal as $pers)
    <br>
        <div class="card">
            <h2><a href="/personal/{{$pers->id}}" >{{$pers->TypeOfAccounting}}</a></h2>
        <h5 class="">Наименование:<span class="badge">{{$pers->Name}}</span></h5>
        </div>
    @endforeach
    {{$personal->links()}}
    @else
    <p>Не найдено записей</p>


    @endif

    @stop
3

3 Answers

1
votes
public function index()
    {
        $user = auth()->user(); // It's already the user model

        $personal = $user->personalAccounting()->orderBy('YOUR_COLUMN')->paginate(2);
        $balance = $user->balance;
        return view('personal.index', compact('personal','balance'));

    }  

Notice personalAccounting() instead of personalAccounting The reason is, when you call the attribute without (), Laravel will load all the data from your DB in a collection. Every modification you do after, will be done with PHP.
When you request with the method using (), you're modifying the QueryBuilder which mean the orderBy and the pagination will be executed by MySQL which will also increase the performance and reduce the memory usage.

0
votes

Give a column name before asc

public function index()
    {
        $user_id=auth()->user()->id;
        $user=User::find($user_id);
        $personal=$user->personalAccounting->orderBy('**your_column_name**','asc')->paginate(2);
        $balance=$user->balance;
        return view('personal.index', compact('personal','balance'));

} 
0
votes
Try to use latest().

public function index()
    {
        $user_id=auth()->user()->id;
        $user=User::find($user_id);
        $personal=$user->personalAccounting->latest('***Add column name***')->paginate(2);
        $balance=$user->balance;
        return view('personal.index', compact('personal','balance'));

    }