What’s wrong? BD + Laravel

Asked

Viewed 228 times

5

I have a form in Lade taking the values of the database. In it I have a field date not required to be filled in. When you enter 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>

2 answers

5


You can use the if in blade.

By doing so you check if the field is filled. He’s setting this date because of the function date() PHP. Since he has nothing, he puts this.

<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>

1

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

A good way to remedy this is by making 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);
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.