Noob Coder
Noob Coder

Reputation: 2897

PHP Laravel form to take day/hour input and set expire time

I want to make a form of user posts. The form will contain post title, post description and post expire time. There will be a database column where I will store the post expire time. Table columns will be:

id | user_id | post_title | post_description | post_status | post_expire_time

Suppose user has given 4 hours in the expire time. The post_status will be not-expired by default and. After 4 hour, the post_status will be converted to expired. How to do that in a Laravel app?

Upvotes: 0

Views: 1192

Answers (2)

Pᴇʜ
Pᴇʜ

Reputation: 57743

I can imagine 2 ways to do this:

Way 1: Save how long the post lives and remember the time of post creation

  • In your database field post_expire_hours you save the hours (or minutes, depends on what the shortest time period you want to allow) the post is considered as not-expired
    (e.g. 4 as integer).
  • In a second field post_created you save when the post was created
    (e.g. 2016-04-28 12:00 as timestamp).

The post status is not required as a database field because it can be calculated from:

if (now > post_created + post_expire_hours) {
    // expired
} else {
    // not-expired
}

In this way you are able to determine how long the post was alive by looking into post_expire_hours.

Way 2: Save the exact point in time when the post expires

  • In your database field post_expire_time you save the exact time when the post expires
    (e.g. 2016-04-28 16:00 as timestamp).

The post status is not required as a database field because it is calculated from:

if (now > post_expire_time) {
    // expired
} else {
    // not-expired
}

In this way you are not able to determine how long the post was alive.

Upvotes: 1

Martin Wickman
Martin Wickman

Reputation: 19925

You need something that updates the rows automatically. Fortunately, Laravel has Task Scheduling for that.

To use it, you must create one (1) cronjob which runs each minute. You then configure your schedule in code. Something like this:

// In the App\Console\Kernel class:

protected function schedule(Schedule $schedule)
{
    $schedule->call(function () {
        // Update your post_status here 
    })->hourly();
}

Upvotes: 0

Related Questions