What's going wrong? BD + Laravel

5

I'm having a blade form picking up the values from the database. In it I have a date field not required to be filled. When you register an empty date, the results screen displays the date "01/01/1970" . How do I change this behavior? I would like it to appear empty when the variable is empty.

<th><a href="{{ URL::to('contas?sort=datapagamento') }}">Data de Pagamento</a></th>
<td>{{ date("d/m/Y", strtotime($conta->datapagamento)) }}</td>
    
asked by anonymous 13.01.2017 / 17:33

2 answers

5

You can use if in blade .

By doing so you check if the field is filled. It is putting that date because of the date() function of PHP. Since he has nothing at all, he puts it on.

<th>
    <a href="{{ URL::to('contas?sort=datapagamento') }}">
       Data de Pagamento
    </a>
</th>

<td>
    @if($conta->datapagamento)
        {{ date("d/m/Y", strtotime($conta->datapagamento)) }}
    @else
       Sem Data
    @endif
</td>
    
13.01.2017 / 17:36
1

When the 01/01/1970 date appears it is very likely that the data is arriving as YYYY-MM-DD and you are having it show d / m / Y and this error occurs.

A good way to remedy this is by doing a helper

<?php

namespace App\Domains\Helpers;

use DateTime;

class DataHelper
{
    const FORMATO_BR = 'd/m/Y';
    const FORMATO_US = 'Y-m-d';

    public static function toBR($data)
    {
        if ($data === '0000-00-00') {
            return '00/00/0000';
        }
        return DateTime::createFromFormat(self::FORMATO_US, $data)->format(self::FORMATO_BR);
    }

    public static function toUS($data)
    {
        if ($data === '00/00/0000') {
            return '0000-00-00';
        }
        return DateTime::createFromFormat(self::FORMATO_BR, $data)->format(self::FORMATO_US);
    }
}
    
13.01.2017 / 19:11