【问题标题】:Laravel: prevent user from accessing past and future eventsLaravel:阻止用户访问过去和未来的事件
【发布时间】:2016-07-26 16:15:31
【问题描述】:

我有一个带有事件的 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

如何预防?

【问题讨论】:

    标签: laravel laravel-5.2


    【解决方案1】:

    您可以使用带有附加子句的 findOrFail() 方法。

    public function show($eventId)
    {
        $now = Carbon::now();
        $event = Event::where('event_startdate', '<=', $now)
            ->where('event_closedate', '>=', $now)
            ->findOrFail($eventId);
    
        //returning specific view
    }
    

    【讨论】:

    • 这就像一个魅力。我自己应该考虑过那个:-)
    猜你喜欢
    • 2016-08-09
    • 1970-01-01
    • 2020-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多