Search code examples
laraveldatedatetimeif-statementreport

Laravel always show 01-Jan-1970 / 01-Jan-1970 in my report when date "from" and "to" is empty


i try to make my report showing "All" instead of default date value "{ 01-Jan-1970 / 01-Jan-1970 }" when the date is empty, i've read other people similar cases here and tried the solution but it doesn't work to me i use date instead of datetime here, and my $from and $to just a field not a part of column in my database, i just use this to filter my report before

StockinController.php

public function print(Request $req)
    {
      $method = $req->method();

        if ($req->isMethod('post'))
        {
            $from = $req->input('from');
            $to   = $req->input('to');

            $start_date = date('d-M-Y', strtotime($from));
            $end_date = date('d-M-Y', strtotime($to));

            if ($req->has('search'))
            {
                if ($from && $to != null) {
                $search = \App\Stockin::whereBetween('tanggal',[$from,$to])->get();
                return view('transaction.stockin.stockinform',['data_stockin' => $search]);
                } 
                else
                {
                $data_stockin = \App\Stockin::all();
                return view('transaction.stockin.stockinform',['data_stockin' => $data_stockin]);
                }

            } 
            elseif ($req->has('exportPDF'))
            { 
                if ($from && $to != null) {
                $PDFReport = \App\Stockin::whereBetween('tanggal',[$from,$to])->get();
                $pdf = PDF::loadView('transaction.stockin.stockin_pdf', ['data_stockin' => $PDFReport,'from' => $start_date, 'to' => $end_date])->setPaper('a4');
                  return $pdf->stream();
                }
                else
                {
                  $PDFReport =  \App\Stockin::all();
                  $pdf = PDF::loadView('transaction.stockin.stockin_pdf', ['data_stockin' => $PDFReport,'from' => $start_date, 'to' => $end_date])->setPaper('a4');
                  return $pdf->stream();
                }
            }  
        }
    } 

stockin_pdf.blade.php

<center>
    <h5>STOCK-IN REPORT</h5>
    <hr>
    @if($from && $to != null) {
        <small>{{$from}}  /  {{$to}} </small>
    }
    @else {
        <small>All</small>
    }
    @endif 
</center>

thank you in advance :)


Solution

  • You are getting date 01-Jan-1970 because string passed to date() is either empty string or null.

    Try something like this:

    $start_date = !empty($from) ? date('d-M-Y', strtotime($from)) : null;
    $end_date = !empty($to) ? date('d-M-Y', strtotime($to)) : null;