Search code examples
phpmysqlexcellaravelexport-to-excel

Excel export only weekly tickets (Support ticket website) - Laravel


I'm currently working on Laravel for the first time and i'm stuck with an issue. I have an export excel button on my tickets list page but It exports all the tickets ever created. Is there a way to only export weekly tickets in excel format based on the current date?

excel form :

@foreach (\App\Tickets::All() as $ticket)
    <tr>
    <td>{{ $ticket->societe}}</td>
    <td>{{ $ticket->intervenant}}</td>
    <td>{{ $ticket->assistance->level}}</td>
    <td>{{ $ticket->message}}</td>
    <td>{{ $ticket->urgence->niveau}}</td>
    <td>{{ $ticket->statut}}</td>
    <td>{{ $ticket->utilisateur->name}}</td>
    </tr>
  @endforeach

Excel function in ticketscontroller :

public function exportxls(){
      Excel::create('tickets', function($excel){
        $excel->sheet('tickets', function($sheet){
          $sheet->loadView('export.ticketsexcel');
        })->export('xls');
      });
      return redirect('/');
    }

Thanks in advance.


Solution

  • You should have sent data from controller to the view and export only weekly tickets you can modify your query.

    public function exportxls(){
      $weeklyTickets = \App\Tickets::whereBetween('created_at', array(date("Y-m-d", strtotime("-7 days")), date('Y-m-d'))->get();
    
      Excel::create('tickets', function($excel) use ($weeklyTickets){
        $excel->sheet('tickets', function($sheet) use ($weeklyTickets){
          $sheet->loadView('export.ticketsexcel', array('weeklyTickets' => $weeklyTickets));
        })->export('xls');
      });
      return redirect('/');
    }
    

    In this function change "created_at" field according to your database field.

    And in view you can modify it like this:

    @foreach ($weeklyTickets as $ticket)
    <tr>
    <td>{{ $ticket->societe}}</td>
    <td>{{ $ticket->intervenant}}</td>
    <td>{{ $ticket->assistance->level}}</td>
    <td>{{ $ticket->message}}</td>
    <td>{{ $ticket->urgence->niveau}}</td>
    <td>{{ $ticket->statut}}</td>
    <td>{{ $ticket->utilisateur->name}}</td>
    </tr>
    @endforeach
    

    Hope this helps you.