Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

clat23's avatar

LengthAwarePaginator could not be converted to int

Here's the full error:

Object of class Illuminate\Pagination\LengthAwarePaginator could not be converted to int (View: /home/vagrant/Code/myapp/resources/views/sales/index.blade.php)

SalesController.php:

<?php

namespace App\Http\Controllers;

use App\Sale;
use Illuminate\Http\Request;

class SalesController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');

        // $this->middleware('subscribed');
    }

    public function index()
    {
        // Retrieve processed sales
        $processedSales = (new Sale)->getProcessed();

        return view('/sales/index')->with([
          'processedSales' => $processedSales
        ]);
    }

Sale.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Auth;
use Camroncade\Timezone\Facades\Timezone;

class Sale extends Model
{
    /**
     * The attributes that should be mutated to dates (Carbon instance).
     *
     * @var array
     */
    protected $dates = [
        'created_at',
        'updated_at',
        'sale_date'
    ];

    public function source()
    {
        return $this->belongsTo(Source::class);
    }

    public function getProcessed() {
        $processedSales = Sale::where('user_id', Auth::user()->id)
            ->where('processed', '=', 1)
            ->orderBy('sale_date', 'desc')
            ->paginate(1);

        foreach ($processedSales as $sale) {
            $sale->sale_date = Timezone::convertFromUTC($sale->sale_date, Auth::user()->timezone);
        }

        return $processedSales;
    }

resources/views/sales/index.blade.php

@extends('spark::layouts.app')

@section('content')
<home :user="user" inline-template>
    <!-- Application Dashboard -->
    <div class="row">
        <div class="col-md-12">
            <!-- Processed Sales Table -->
            <div class="panel panel-default">
                <div class="panel-heading">Processed Sales</div>
                <div class="panel-body">
                    @if ($processedSales > 0)
                        <div class="table-responsive">
                            <table class="table table-condensed">
                                <thead>
                                    <tr>
                                        <th>Sale Date</th>
                                        <th class="text-center">Quantity</th>
                                        <th class="text-center">Sale Price</th>
                                        <th class="text-center">Item Cost</th>
                                        <th class="text-center">Profit</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach ($processedSales as $sale)
                                        <tr>
                                            <td>{{ $sale->sale_date->format('m-d-Y') }}</td>
                                            <td class="text-center">{{ $sale->quantity_sold }}</td>
                                            <td class="text-center">{{ $sale->sale_price }}</td>
                                            <td class="text-center text-danger">({{ $sale->seller_cost }})</td>
                                            @if (strpos($sale->profit, '-') !== false)
                                                <td class="text-danger text-center"><strong>({{ $sale->profit }})</strong></td>
                                            @else
                                                <td class="text-success text-center"><strong>{{ $sale->profit }}</strong></td>
                                            @endif
                                            <td>
                                                <span class="glyphicon glyphicon-list-alt" data-toggle="modal" data-target="#saleInfo-{{ $sale->order_id }}"></span>&nbsp;&nbsp;
                                                <span class="glyphicon glyphicon-trash" data-toggle="modal" data-target="#confirmDelete-{{ $sale->id }}"></span>
                                            </td>
                                        </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                        {{ $processedSales->links() }}
                        @foreach ($processedSales as $sale)
                            @if ($sale->processed)
                                <div id="saleInfo-{{ $sale->order_id }}" class="modal fade" role="dialog">
                                    <div class="modal-dialog">
                                        <!-- Modal content-->
                                        <div class="modal-content">
                                            <div class="modal-header">
                                                <button type="button" class="close" data-dismiss="modal">&times;</button>
                                                <h4 class="modal-title">Detailed Sale Information</h4>
                                            </div>
                                            <div class="modal-body">
                                                <p><strong>Date of Sale: </strong>{{ $sale->sale_date->format('m-d-Y') }}<br>
                                                <strong>Sale Price: </strong>{{ $sale->sale_price }}<br>
                                                <strong>Quantity Sold: </strong>{{ $sale->quantity_sold }}<br>
                                                <strong>Your Cost: </strong>{{ $sale->seller_cost }}<br>
                                                <strong>Your Net Profit: </strong>{{ $sale->profit }}<br>
                                                <strong>Buyer Name: </strong>{{ $sale->buyer_name }}<br>
                                                <strong>Buyer E-Mail: </strong>{{ $sale->buyer_email }}</p><br>
                                            </div>
                                            <div class="modal-footer">
                                                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div id="confirmDelete-{{ $sale->id }}" class="modal fade" role="dialog">
                                    <div class="modal-dialog modal-sm">
                                        <!-- Modal content-->
                                        <div class="modal-content">
                                            <div class="modal-header">
                                                <button type="button" class="close" data-dismiss="modal">&times;</button>
                                                <h4 class="modal-title">Delete Confirmation</h4>
                                            </div>
                                            <div class="modal-body">
                                                <p><strong>Are you sure you want to delete this sale?</strong></p>
                                            </div>
                                            <div class="modal-footer">
                                                <form method="POST" action="/sales/{{ $sale->id }}">
                                                    {{ method_field('DELETE') }}
                                                    {{ csrf_field() }}
                                                    <button type="submit" class="btn btn-primary">Delete</button>
                                                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                                                </form>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            @endif
                        @endforeach
                    @else
                        <p>There are no processed sales at this time.</p>
                    @endif
                </div>
            </div>
        </div>
    </div>
</home>
@endsection

What's causing the error? Any help would be appreciated!

0 likes
24 replies
jlrdw's avatar

This belongs in a controller

$processedSales = Sale::where('user_id', Auth::user()->id)
            ->where('processed', '=', 1)
            ->orderBy('sale_date', 'desc')
            ->paginate(1);

I don't use spark, but in laravel anyway I'd have it in a controller.

clat23's avatar

@jlrdw First off, thanks for the response! But I moved it to the controller just as you suggested and I still have the same error.

SalesController.php:

<?php

namespace App\Http\Controllers;

use App\Sale;
use Illuminate\Http\Request;

class SalesController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');

        // $this->middleware('subscribed');
    }

    public function index()
    {
        // Retrieve processed sales
        $processedSales = (new Sale)->paginate(1);

        return view('/sales/index')->with([
          'processedSales' => $processedSales
        ]);
    }

On a separate note, I also have a ListingsController.php and a model Listing.php. I have the paginate method in the model and it works just fine, no errors.

jlrdw's avatar

what happens if you dd or print_r $processedSales, does it kick out results?

clat23's avatar

Yes. When I add {{ dd($processedSales) }} to the view I get this:

LengthAwarePaginator {#401 ▼
  #total: 4
  #lastPage: 4
  #items: Collection {#405 ▼
    #items: array:1 [▼
      0 => Sale {#406 ▼
        #dates: array:3 [▶]
        #connection: "mysql"
        #table: null
        #primaryKey: "id"
        #keyType: "int"
        +incrementing: true
        #with: []
        #withCount: []
        #perPage: 15
        +exists: true
        +wasRecentlyCreated: false
        #attributes: array:27 [▶]
        #original: array:27 [▶]
        #casts: []
        #dateFormat: null
        #appends: []
        #events: []
        #observables: []
        #relations: []
        #touches: []
        +timestamps: true
        #hidden: []
        #visible: []
        #fillable: []
        #guarded: array:1 [▶]
      }
    ]
  }
  #perPage: 1
  #currentPage: 1
  #path: "http://myapp.app/sales"
  #query: []
  #fragment: null
  #pageName: "page"
jlrdw's avatar

Where is LengthAwarePaginator coming from? I don't see where it is in your code?

jlrdw's avatar

I guess spark uses it, my idea of LengthAwarePaginator is something like

$data = DB::table('powners')
                        ->where('oname', 'like', $ownersearch)
                        ->orderBy('oname', 'asc')
                        ->skip($offset)->take($perpage)->get();
        $pagelinks = LengthPager::makeLengthAware($data, $numrows, $perpage, ['t1' => $t1]);
        return view('owner/pownerlist')->with('data', $data)->with('data2', $pagelinks);

just quick example

But are you returning an object or array?

Edit have you tryed

$sale['quantity_sold'] // for example
clat23's avatar

I tried removing @if ($processedSales > 0) from the view (and the corresponding @endif) and it works. So I'm not sure why @if ($processedSales > 0) causes the error:

Object of class Illuminate\Pagination\LengthAwarePaginator could not be converted to int (View: /home/vagrant/Code/myapp/resources/views/sales/index.blade.php)

jlrdw's avatar

$processedSales is the collection (results) not the count. If (! empty .. would have been correct. I don't know how to do ! empty in blade.

1 like
jimmy0699's avatar

i dont know much about pagination but this looks weird to me :

$processedSales = (new Sale)->paginate(1);

have you try change it for:

$processedSales = Sale::paginate(1);

found it in your blade you have line:

 @if ($processedSales > 0)

should be

 @if (sizeof($processedSales) > 0)
clat23's avatar

Ok we're getting somewhere. I replaced @if ($processedSales > 0) with @if (!empty($unprocessedSales)) and it got rid of the error. But now my table is empty.

I think now the problem lies in @foreach ($processedSales as $sale). I tried replacing it with @foreach ($processedSales->items as $sale) but I get this error:

Cannot access protected property Illuminate\Pagination\LengthAwarePaginator::$items

How do I access 'items' in:

LengthAwarePaginator {#401 ▼
  #total: 4
  #lastPage: 4
  #items: Collection {#405 ▼
    #items: array:1 [▼
      0 => Sale {#406 ▼
jlrdw's avatar

Are you returning an array, have you tryed something like

$sale['quantity_sold'] // for example
jlrdw's avatar

Are you sure $unprocessedSales is correct should it be $processedSales

clat23's avatar

@jlrdw

$sale['quantity_sold']

Still gives me an empty result

$unprocessedSales was a mistake. I changed it to $processedSales. Same result....which is not a problem anymore. Now I'm having issues accessing the items in the collection.

clat23's avatar

@jimmy0699 I tried

@foreach ($processedSales as $sale)
{{{ var_dump($sale) }}}
@endforeach 

I'm still getting an empty table.

I tried

{{ dd($sale) }}

Also results in an empty table.

jlrdw's avatar

Try removing this to see if you get results:

foreach ($processedSales as $sale) {
            $sale->sale_date = Timezone::convertFromUTC($sale->sale_date, Auth::user()->timezone);
        }
clat23's avatar

Removed:

foreach ($processedSales as $sale) {
            $sale->sale_date = Timezone::convertFromUTC($sale->sale_date, Auth::user()->timezone);
        }

Still no results.... this is so strange.

jlrdw's avatar

Var_dump right after

public function getProcessed() {
        $processedSales = Sale::where('user_id', Auth::user()->id)
            ->where('processed', '=', 1)
            ->orderBy('sale_date', 'desc')
            ->paginate(1);
            Var_dump($processedSales);

or dd

clat23's avatar

This:

public function getProcessed() {
        $processedSales = Sale::where('user_id', Auth::user()->id)
            ->where('processed', '=', 1)
            ->orderBy('sale_date', 'desc')
            ->paginate(1);
            dd($processedSales);

Gets me this:

LengthAwarePaginator {#405 ▼
  #total: 2
  #lastPage: 2
  #items: Collection {#404 ▼
    #items: array:1 [▼
      0 => Sale {#401 ▶}
    ]
  }
  #perPage: 1
  #currentPage: 1
  #path: "http://myapp.app/sales"
  #query: []
  #fragment: null
  #pageName: "page"
}
jlrdw's avatar

In your browser can you see all the data, is it correct?

clat23's avatar

No data in the browser. I get an empty table. I will try some other things. Thank you for trying to help me @jlrdw

jlrdw's avatar

I meant when you dd($processedSales); was all data correct there? Good luck

whoisthisstud's avatar

Not sure if you ever resolved this or not, but I just had the same issue and resolved it by adjusting the @if statement that contains the object variables and pagination links:

@if( $variable->count() > 0 )
    // The following did NOT work and resulted in the same error.
    // @if( count( $variable ) > 0 )
    // @if( sizeof($variable) > 0 )
    // @if( $variable > 0 )
@endif 

Please or to participate in this conversation.