Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Table -> paginate #1338

Open
odougback opened this issue Mar 16, 2025 · 4 comments
Open

Table -> paginate #1338

odougback opened this issue Mar 16, 2025 · 4 comments

Comments

@odougback
Copy link

odougback commented Mar 16, 2025

Good morning!

Implementing pagination in tables when the data comes from a database was relatively easy. However, I am having trouble implementing pagination in a table generated from JSON data. I am attaching the source files. Could you guide me on how to implement pagination for the table?

@odougback
Copy link
Author


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\EmailAccount;
use Illuminate\Support\Facades\Crypt;

class EmailController extends Controller
{
    public function listEmails(Request $request)
    {
        try {
            $emailAccount = EmailAccount::findOrFail($request->input('account_id'));
            $password = Crypt::decryptString($emailAccount->password);

            $mailbox = "{" . $emailAccount->host . ":" . $emailAccount->port . "/imap/ssl/novalidate-cert}INBOX";
            $imapStream = imap_open($mailbox, $emailAccount->username, $password);

            if ($imapStream === false) {
                return response()->json(['error' => 'Erro IMAP: ' . imap_last_error()], 500);
            }

            $searchCriteria = $request->has('query') && !empty(trim($request->input('query')))
                ? 'SUBJECT "' . trim($request->input('query')) . '"'
                : 'ALL';

            $emails = imap_search($imapStream, $searchCriteria);
            $emailList = [];

            if ($emails) {
                rsort($emails);
                $emails = array_slice($emails, 0, 50);

                foreach ($emails as $emailId) {
                    $header = imap_headerinfo($imapStream, $emailId);
                    $structure = imap_fetchstructure($imapStream, $emailId);

                    $hasAttachment = false;
                    if (isset($structure->parts) && count($structure->parts) > 1) {
                        foreach ($structure->parts as $part) {
                            if (isset($part->disposition) && strtolower($part->disposition) === 'attachment') {
                                $hasAttachment = true;
                                break;
                            }
                        }
                    }

                    $from = $header->from[0]->mailbox ?? 'Desconhecido';
                    $host = $header->from[0]->host ?? 'Desconhecido';
                    $emailFrom = $from . '@' . $host;
                    $subject = $header->subject ?? 'Sem Assunto';
                    $date = isset($header->date) ? date('d/m/Y H:i', strtotime($header->date)) : 'Data desconhecida';

                    $emailList[] = [
                        'id' => $emailId,
                        'subject' => $subject,
                        'from' => $emailFrom,
                        'date' => $date,
                        'has_attachment' => $hasAttachment, // � Indica se há anexo
                        'unseen' => isset($header->Unseen) && $header->Unseen == 'U'
                    ];
                }
            }

            imap_close($imapStream);
            return response()->json($emailList);
        } catch (\Exception $e) {
            return response()->json(['error' => 'Erro ao conectar: ' . $e->getMessage()], 500);
        }
    }
}

@odougback
Copy link
Author


<div class="bg-zinc-50 dark:bg-zinc-900 p-4 rounded-lg">
    <flux:header>
        <h1 class="text-2xl font-bold">E-mails de {{ $account->email }}</h1>

        <flux:spacer />
        <flux:button href="{{ route('email-accounts.index') }}" variant="outline" wire:navigate size="sm">
            Voltar
        </flux:button>
    </flux:header>

    <div class="mt-3">
        <div class="mb-3">
            @if (session()->has('error'))
                <flux:callout variant="danger" icon="check-circle" heading="{{ session('error') }}" />
            @endif
        </div>

        @if (empty($emails))
            <flux:separator class="mb-6" />
            <div class="mb-6 flex justify-center">
                <flux:button icon="inbox" wire:click="fetchEmails">
                    Carregar E-mails
                </flux:button>
            </div>
        @else
            <div class="mb-6 flex gap-2">
                <flux:input wire:model="searchQuery" placeholder="Pesquisar e-mails..." class="w-full" size="base" />
                <flux:button variant="primary" icon="magnifying-glass" wire:click="fetchEmails" size="base">
                    Buscar
                </flux:button>
            </div>

            <flux:table class="bg-white dark:bg-zinc-700 p-4 rounded-lg">
                <flux:table.columns>
                    <flux:table.column class="first:pl-2">Remetente</flux:table.column>
                    <flux:table.column>Assunto</flux:table.column>
                    <flux:table.column>Anexo</flux:table.column>
                    <flux:table.column>Data</flux:table.column>
                </flux:table.columns>
                <flux:table.rows>
                    @foreach ($emails as $email)
                        <flux:table.row>
                            <flux:table.cell class="first:pl-2"> {{ $email['from'] }} </flux:table.cell>
                            <flux:table.cell>{{ Str::limit($email['subject'] ?? 'Sem Assunto', 50) }} </flux:table.cell>
                            <flux:table.cell>
                                @if ($email['has_attachment'])
                                <flux:icon name="paper-clip" />@else<span
                                        class="text-gray-400">�</span>
                                @endif
                            </flux:table.cell>
                            <flux:table.cell>{{ $email['date'] }}</flux:table.cell>
                        </flux:table.row>
                    @endforeach
                </flux:table.rows>
            </flux:table>

        @endif
    </div>
</div>

@odougback
Copy link
Author


<?php
namespace App\Livewire\EmailAccounts;

use Livewire\Component;
use Illuminate\Support\Facades\Http;
use App\Models\EmailAccount;

class EmailList extends Component
{
    public $emails = []; // 🔹 Iniciar vazio (não carregar automaticamente)
    public $accountId;
    public $account;
    public $searchQuery = ''; // 🔍 Variável para pesquisa

    public function mount($id)
    {
        $this->accountId = $id;
        $this->account = EmailAccount::findOrFail($id);
    }

    public function fetchEmails()
    {
        try {
            $apiUrl = config('app.api_url', env('API_URL')) . '/emails/list';

            // 🔹 Enviar o ID da conta e a pesquisa para a API
            $response = Http::post($apiUrl, [
                'account_id' => $this->accountId,
                'query' => $this->searchQuery
            ]);

            if ($response->successful()) {
                $this->emails = $response->json();
            } else {
                session()->flash('error', 'Erro ao carregar os e-mails da API.');
            }
        } catch (\Exception $e) {
            session()->flash('error', 'Erro de conexão: ' . $e->getMessage());
        }
    }

    public function render()
    {
        return view('livewire.email-accounts.email-list', [
            'emails' => $this->emails,
            'account' => $this->account
        ]);
    }
}

@jeffchown
Copy link

jeffchown commented Mar 16, 2025

@odougback This isn't a Flux question. What it looks like you are asking is how to paginate a JSON list of emails. More a Laravel question re: pagination.

This should help get your started: https://codecourse.com/articles/paginating-a-collection-in-laravel

@joshhanley joshhanley assigned joshhanley and unassigned joshhanley Mar 17, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants