我有一个带有事件的Laravel应用程序,其中一些发生在过去,其中一些是最新的,一些将在未来组织。表'事件'如下所示:
+----+-------------+------------+-------------------+---------------------+---------------------------+---------------------+---------------------+
| id | category_id | event_name | event_description | event_startdate | event_closedate | created_at | updated_at |
+----+-------------+------------+-------------------+---------------------+---------------------------+---------------------+---------------------+
| 1 | 1 | Event 1 | Event 1 | 2016-05-02 00:00:00 | 2016-06-30 00:00:00 | 2016-07-07 15:59:03 | 2016-07-08 12:26:07 |
| 2 | 1 | Event 2 | Event 2 | 2016-06-02 00:00:00 | 2016-07-30 00:00:00 | 2016-07-07 15:59:03 | 2016-07-08 12:26:22 |
| 3 | 2 | Event 3 | Event 3 | 2016-07-02 00:00:00 | 2016-08-19 00:00:00 | 2016-07-07 15:59:03 | 2016-07-08 12:27:04 |
| 4 | 2 | Event 4 | Event 4 | 2016-09-01 00:00:00 | 2016-10-30 00:00:00 | 2016-07-07 15:59:03 | 2016-07-07 15:59:03 |
+----+-------------+------------+-------------------+---------------------+---------------------------+---------------------+---------------------+
并且每个事件包含许多项目,表格如下:
+----+------------+-----------+-----------------------+
| id | event_id | item_name | item_description |
+----+------------+-----------+-----------------------+
| 1 | 1 | Item 1 | Item 1 - description |
| 2 | 1 | Item 2 | Item 2 - description |
| 3 | 2 | Item 3 | Item 3 - description |
| 4 | 2 | Item 4 | Item 4 - description |
| 5 | 3 | Item 5 | Item 5 - description |
我正在主页上显示当前事件。在此示例中,事件2和3是当前事件。每个事件都有一个链接供用户查看属于该事件的项目。
http://localhost:5000/event/2/items
http://localhost:5000/event/3/items
我想阻止用户查看非当前事件(例如过去和将来的事件)。在此示例中,这意味着如果用户尝试访问,则应显示“未找到”页面(或类似页面):
http://localhost:5000/event/1/items
http://localhost:5000/event/4/items
如何防止这种情况?
答案 0 :(得分:4)
您可以将findOrFail()方法与附加子句一起使用。
public function show($eventId)
{
$now = Carbon::now();
$event = Event::where('event_startdate', '<=', $now)
->where('event_closedate', '>=', $now)
->findOrFail($eventId);
//returning specific view
}