There a blog create and post functionality in my project.When I create a post I am getting date at created_at field is Jan 01 1970. When I tried to debug it,got null value for this field.I am unable to figure it out.
blog.blade.php
@foreach($blogs as $blog)
<div class="blog-container">
<div class="blog-info">
<h3><a href="https://africainnovationmarket.org/blog/testing-blog-by-acropolis-11/" title="Testing Blog by Acropolis 11" rel="bookmark">{{$blog->name}}</a></h3> <div class="created-blog-info">
<div class="create-time"><?php echo date("M d Y",strtotime($blog->created_at));
echo $blog->created_at;
?> </div>
<?php $name = DB::table('userdetails')->where('id',$blog->created_by)->get(); ?>
<div class="create-author">@if($blog->created_by > 0 ) {{$name[0]->firstname}} {{$name[0]->lastname}} @else Admin @endif</div>
<div class="sharelinks" style="float:right"></div>
</div>
@endforeach
BlogController.php
public function blog()
{
$blogs = DB::table('blogs')->where('delete_status','0')->get();
return view("home.blog",compact("blogs"));
}
This is my blog table structure
CREATE TABLE IF NOT EXISTS `blogs` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`content` text COLLATE utf8mb4_unicode_ci NOT NULL,
`tags` varchar(55) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_by` int(11) DEFAULT NULL,
`updated_by` int(11) DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`delete_status` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
when I create a blog, created_at field should take that date so that I can get exact value of created_at field instead of null.How should I do it?
use now()
while insert the data ref link https://laravel.com/docs/7.x/helpers#method-now
DB::table('blogs')->insert([
'created_at' => now(), //now is a helper function in laravel
'updated_at' => now(),
]);
or
Blog::create() // it will automatically create both
If you create a blog model this would be done by Laravel automatically.
You are getting created_at
value as null
because you did not insert it. Because you did not use a model, you have to insert it manually or you can make a model.
Manually,
DB::table('blogs')->insert(['created_at'= > now()]);
For unix timestamp use now()->timestamp
Or make a model,
php artisan make:model Blog
It will create a model. Then You have to create a blog.
Blog::create([]);
By create()
method it will insert created_at
, updated_at
value autometically.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.