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

nickdavies07's avatar

Returning first() with maatwebsite/laravel-excel

Is it possible to just return only one row with this Excel export package?

I need to export the last supplier that the currently authenticated user inserted.

I need to do something like this...

class SuppliersExport implements FromQuery
{
    /**
     * @return \Illuminate\Database\Query\Builder
     */
    public function query()
    {
        return Supplier::where('user_id', auth()->id())->first();
    }
}
0 likes
7 replies
Nakov's avatar

Have you tried using Exportable trait, like this:

namespace App\Exports;

use App\Supplier;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\Exportable;

class SuppliersExport implements FromQuery
{
    use Exportable;

    public function query()
    {
        // since you need the last one, not the first
        return Supplier::query()->where('user_id', auth()->id())->last(); 
    }
}

You can also use ->latest()->first() to order the suppliers in descending order and get the first item, in case the last is not the newest one.

nickdavies07's avatar

@NAKOV - Apologies, my mistake I did mean to write ->last() above.

Unfortunately, using ->last() gives me an undefined method exception BadMethodCallException Call to undefined method Illuminate\Database\Eloquent\Builder::last().

Nakov's avatar

@NICKDAVIES07 - Yes, the last method is from the collection and not on the Query Builder so try using ->latest()->first() instead.

nickdavies07's avatar

@NAKOV - Thanks. Still no luck unfortunately.

It seems to strip off everything after the where() clause, so the exported CSV is returning all suppliers where the user_id is equal to the auth ID, ignoring latest and first?

matttonks11's avatar

If your exporting a collection you need to update your class

use Maatwebsite\Excel\Concerns\FromCollection;

class SuppliersExport implements FromCollection
{
  
    public function collection()
    {
        return Supplier::query()->where('user_id', auth()->id())->latest()->first();
    }
}

You can see more here https://docs.laravel-excel.com/3.1/exports/collection.html

Nakov's avatar
Nakov
Best Answer
Level 73

@NICKDAVIES07 - Yes, you are right. I succeeded now using FromArray instead like this:

use Maatwebsite\Excel\Concerns\FromArray;


class SuppliersExport implements FromArray
{
    use Exportable;

    /**
     * @return array
     */
    public function array(): array
    {
        $supplier = Supplier::where('user_id', auth()->id())->latest()->first();
        return [$supplier->toArray()];
    }
}
nickdavies07's avatar

@NAKOV - Thanks

This works great although a little annoying to have to convert to an array.

Please or to participate in this conversation.