Display creation date (created_at) in Laravel 5.5 post

Asked

Viewed 2,119 times

3

Good morning guys, I am very beginner in Lisbon and I have a small problem that I am not able to solve. In a post view, I need to display the date the post was created. In the database it would be the created_at column (timestamp format). But I don’t know why, this field is printing a null result. Can anyone tell me how to solve this? I was trying to use it this way:

{{ Carbon\Carbon::parse($noticia->created_at)->format('d/m/Y') }}

But the above code only displays the current date, I believe that because the $noticia->created_at field is coming null;

Follow the code of the full website:

Model

namespace App\Models;        
use Illuminate\Database\Eloquent\Model;
    use App\Traits\Sluggable;

    class Post extends Model
    {
        use Sluggable;
        protected static $sluggable = 'titulo';
        public static $storage      = 'post';
        protected $table            = 'post';
        protected $dates            = ['periodo_inicio', 'periodo_fim', 'created_at', 'updated_at'];
        protected $fillable         = [
            'id', 'titulo', 'conteudo', 'periodo_inicio', 'periodo_fim', 'imagem', 'qtd_views',
            'active', 'destaque', 'slug', 'resumo', 'created_at', 'updated_at', 'title_seo', 'description_seo'
        ];
    }

Controller

public function noticiasDetalhe($slug)
    {
        $base_posts_destaques = Post::where('active', 1)->where('destaque', 1)->orderBy('created_at', 'desc')->take(4)->get();

        $noticia = Post::where('slug', $slug)->leftjoin('post_rel_categorias', 'post_rel_categorias.post_id', '=', 'post.id')->first();

        $buscar = '';
        $page_title = '';
        $page_description = '';

        if($noticia) {

            $noticia->update(['qtd_views'=>($noticia->qtd_views + 1)]);
            if($noticia->title_seo != "") {
                $page_title = $noticia->title_seo . " - Berkan";
            } else {
                $page_title = $noticia->titulo . " - Berkan";
            }

            if($noticia->description_seo != "") {
                $page_description = $noticia->description_seo . " - Berkan";
            } else {
                $page_description = $noticia->resumo . " - Berkan";
            }

            $categorias = Post_Categoria::where('active', 1)->get();

            $base_posts = Post::where('post_rel_categorias.post_categoria_id', $noticia->post_categoria_id)
                ->where('post_rel_categorias.id', '<>', $noticia->id)
                ->leftjoin('post_rel_categorias', 'post_rel_categorias.post_id', '=', 'post.id')
                ->select(
                    'post_rel_categorias.id',
                    'post_rel_categorias.post_id',
                    'post.id',
                    'post.titulo',
                    'post.imagem',
                    'post.slug',
                    'post.created_at'
            )->orderBy('created_at', 'desc')->take(3)->get();

        } else {
            abort(404);
            die();
        }

        return view('noticias-detalhe', compact('noticia', 'base_posts_destaques', 'base_posts', 'categorias', 'page_title', 'page_description'));
    }

If anyone knows how to handle it I’d appreciate it.

print dd($noticia);

Post {#419 ▼
  #table: "post"
  #dates: array:4 [▼
    0 => "periodo_inicio"
    1 => "periodo_fim"
    2 => "created_at"
    3 => "updated_at"
  ]
  #fillable: array:15 [▼
    0 => "id"
    1 => "titulo"
    2 => "conteudo"
    3 => "periodo_inicio"
    4 => "periodo_fim"
    5 => "imagem"
    6 => "qtd_views"
    7 => "active"
    8 => "destaque"
    9 => "slug"
    10 => "resumo"
    11 => "created_at"
    12 => "updated_at"
    13 => "title_seo"
    14 => "description_seo"
  ]
  #connection: "mysql"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:18 [▼
    "id" => "53"
    "titulo" => "Educação profissional continuada para o auditor independente"
    "slug" => "educacao-profissional-continuada-para-o-auditor-independente"
    "resumo" => "Como uma forma de valorizar a profissão do contador diante da sociedade e das empresas, o Conselho Federal de Contabilidade (CFC) estabeleceu a norma de educaçã ▶"
    "conteudo" => ""
    "imagem" => "post/N9kKOUODlFnISmF8pyO8hvJR2nDMWoLHjz5cAcmO.jpeg"
    "periodo_inicio" => null
    "periodo_fim" => null
    "active" => "1"
    "destaque" => "0"
    "qtd_views" => "272"
    "deleted_at" => null
    "created_at" => null
    "updated_at" => null
    "title_seo" => "Educação profissional continuada para o auditor independente"
    "description_seo" => "Como uma forma de valorizar a profissão do contador diante da sociedade e das empresas, o Conselho Federal de Contabilidade (CFC) estabeleceu a norma de educaçã ▶"
    "post_id" => "43"
    "post_categoria_id" => "5"
  ]
  #original: array:18 [▼
    "id" => "53"
    "titulo" => "Educação profissional continuada para o auditor independente"
    "slug" => "educacao-profissional-continuada-para-o-auditor-independente"
    "resumo" => "Como uma forma de valorizar a profissão do contador diante da sociedade e das empresas, o Conselho Federal de Contabilidade (CFC) estabeleceu a norma de educaçã ▶" 
    "imagem" => "post/N9kKOUODlFnISmF8pyO8hvJR2nDMWoLHjz5cAcmO.jpeg"
    "periodo_inicio" => null
    "periodo_fim" => null
    "active" => "1"
    "destaque" => "0"
    "qtd_views" => "272"
    "deleted_at" => null
    "created_at" => null
    "updated_at" => null
    "title_seo" => "Educação profissional continuada para o auditor independente"
    "description_seo" => "Como uma forma de valorizar a profissão do contador diante da sociedade e das empresas, o Conselho Federal de Contabilidade (CFC) estabeleceu a norma de educaçã ▶"
    "post_id" => "43"
    "post_categoria_id" => "5"
  ]
  #changes: []
  #casts: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #guarded: array:1 [▼
    0 => "*"
  ]
}

Thank you

  • 1

    If I’m not mistaken, in $noticia->created_at, created_at is already an instance of Carbon by default, so try using only $noticia->created_at->format('d/m/Y').

  • you gave a var_dump on created_at?

  • The news does not return a vector?

  • Have you tried $noticia->created_at->format('d/m/Y') because it is already of the Carbon instance that you have configured in your model

  • I’ve tried this: $noticia->created_at->format(’d/m/Y') but it doesn’t work either. It even gives an error in Laravel. @Viniciuslourenço

  • I’ve tried @Virgilionovic, but unfortunately there’s a 500 error on Laravel

  • @Ademilsonsantanadasilva already yes, but does not return anything. In the bank the fields are not empty.

  • @Saul What is the error, because I have already written codes that format the date this way without problems ? You can also withdraw the mention of created_at of the variable $dates.

  • Now that I saw your model is not right missed adding traits and how your base is recording it.

  • @Viniciuslourenço then the error that is giving is this: "Call to a Member Function format() on null" I believe it is because it is returning null value

  • @Virgilionovic it automatically records when creating the post, using the Laravel standard

  • Let Saul show his record!

  • @Saul makes a test please run a dd($news); below it and mana the print here for us.

  • @Bulfaitelo I circled what you asked me and updated, from a look above. I edited to make more visible the code. Thanks

  • the problem is that the information does not seem to exist in the database, check if really the system is saving it,

  • can look directly in the database and check if this data exists if yes updates the question with the structure of this table ai with the result of select * from noticias

  • @Bulfaitelo I believe I found the problem, missing find the solition =D The problem is in this line of Controller code: $noticia = Post::Where('Slug', $Slug)->leftjoin('post_rel_categorias', 'post_rel_categorias.post_id', '=', 'post.id')->first(); But specifically in leftjoin with the table 'post_rel_categories'. I believe that this table has the created_at field (I’ll check in the bank) and this should be giving conflict. Do you know how I can solve this by staying that leftjoin? Thanks

  • test removes the innerjoin(); and check the result of dd($noticia); if it returns we kill the problem;

  • I removed and now appeared the date in the result =) ie the problem is right there @Bulfaitelo

  • I’ll answer test to see if it works.

  • @Saul tests there and gives me a feedback, if possible already runs a dd($news); for you to see how he is behaving

Show 16 more comments

2 answers

2


As we saw on Chat the problem is related to innerJoin who is subscribing to the information table news,

$noticia = Post::where('slug', $slug)
    ->select('post.*')
    ->leftjoin('post_rel_categorias', 'post_rel_categorias.post_id', '=', 'post.id')
    ->first();

I added select to be able to separate the data from the Internet with the news data,

OBS. exchange the post. * for the name of your table.

another tip to make your life easier and inside the model

Add the following line:

protected $dates = [
        'created_at',
        'updated_at',
    ];

So when calling information for example:

$noticia->created_at; you can add the format method to return it formatted, for example:

$noticia->create_at->format('d/m/Y');
  • 100% Thanks for your help.

-1

No need to put created_at and updated_at in fillable, the even manage these fields for you

  • Your answer could come with some references, right?! D

Browser other questions tagged

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