I'm learning Laravel and I've created a basic blog. Now, I'm trying to create something similar to an autoblog where posts change status based on either start_date or end_date. So I've created an enum table in my migration with the statuses I need to use. Right now, what I'm trying to do is change the post status to Upcoming if the date and time are greater than today but I'm not having any luck. Initially, I created an event and put the code below in the listener but is working (or not working) in the same way as in the observer. I read that it would be better in the observer if there will be several events.
The flow would be, when the post is created, check the start_date and change the status if the date is greater than today. The code below changes the status to Upcoming if I change it to creating, instead of created but it still doesn't take the start_date into account because it adds it to every post, regardless of the start_date. I tried using an if statement but I kept getting stuck. What am I missing or doing wrong?
Eventually, my goal is for the posts to change the status automatically without any user-initiated action. Perhaps, I could use Laravel queues for that but I haven't got that far yet. For the moment, I'm trying to get past this one.
<?php
namespace App\Observers;
use App\Models\Post;
use Carbon\Carbon;
class PostObserver
{
public function created(Post $post)
{
$post = Post::whereDate('start_date', '>', Carbon::now()->toDateString(){
$post->post_status = 1 // 1 = Upcoming status
});
}
}
if(Carbon::parse($post->start_date) > Carbon::now() { $post->post_status = 1 }. Also try with creating instead created