i have a two tables, days and posts.
Days table

id  |  day  
----------
1   | Day1
2   | Day2
3   | Day3
4   | Day4
5   | Day5
6   | Day6
7   | Day7
8   | Day8
9   | Day9
10  | Day10
11  | Day11
12  | Day12


Posts table

id  |  day  |  posts
---------------------------
1   | 1    |  Day1Text
2   | 1    |  Day1Text
1   | 1    |  Day1Text
2   | 2    |  Day2Text
1   | 2    |  Day2Text
2   | 3    |  Day3Text
1   | 4    |  Day4Text
2   | 5    |  Day5Text

I have a 12 days and each days have a different posts, every day at 10.00 am this change, example Today(Day1) and only 1st day posts will appear. Tomorrow at 10.00 am 2nd day posts will appear. When the 12th day ends, this loop will return to the beginning and start again 1st day. How can i do this?

2 Answers

1
leuquim On Best Solutions

First off you want to know how to cycle over the posts as days go by. As input we need at least 12 different days, so we can use the current day of the month or year. If we take the day of the year:

Carbon::now()->dayOfYear  //e.g. int(137)

We can now calculate its mod against the number of posts, which will always return a number between 0 and 11. If we add 1 we'll have a number between 1 - 12. E.g:

137 % 12 = 5  // 5 + 1 = 6
120 % 12 = 0  // 0 + 1 = 1
347 % 12 = 11 // 11 + 1 = 12

At this point, we know what post we need to display each day, but we're not controlling the hour it should start displaying. To fix this, one way would be to consider the days change at the time you want the posts to change, aligning both makes things easier. As we don't want to offset the server timezone, we can just offset the date we pick by 10h meaning that a new day will begin once the current day gets to 10AM:

Carbon::now()->subHours(10)->dayOfYear

Now we can use the resulting mod value to build the necessary query to display the post.

0
Ross Wilson On

From the looks of it you don't really need the if statement so for this you could either use the englishDayOfWeek getter or just use php's date format

i.e.

$results = Post::where('Day', now()->englishDayOfWeek)->get()

or

$results = Post::where('Day', now()->format('l'))->get()