TheWebs TheWebs - 1 year ago 39
PHP Question

How do I update a record create in the same day or create a new record if its a new day? (Laravel 5.2)

So in laravel if I have a record that was created today I can call update or save as I update the record. Awesome.

But what if its tomorrow? How do I say, hey is it still yesterday? no? Ok lets create a new record. For example:

id: 1,
post_id: 1
viewed_times: 3
create_at: today

So I can update it since it's today. But now lets assume its tomorrow (after 12:00 AM).

Now instead of updating the record, since it's tomorrow, I want to create a new record to say:

id: 2,
post_id: 1
viewed_times: 2
create_at: tomorrow

So now you can see we have a new record with the same post id and the views for the new day (tomorrow) is set to 2.

Whats the best way to say: Is it today or is it tomorrow? If its today then update the existing record, if its tomorrow, then create a new record.

Note: If I could use carbon that would be amazing to make it simpler.

Answer Source

You can use

$today = Carbon\Carbon::today();

then get the tomorrow of your created record like this :



    //it's tomorrow insert new record 
    //it's the same day just update the record :)