【问题标题】:Laravel 4 Validator - Validate if post belongs to category that belongs to current userLaravel 4 Validator - 验证帖子是否属于属于当前用户的类别
【发布时间】:2014-10-25 21:41:19
【问题描述】:

我有 3 个表,“links”、“links_categories”和“users”,我希望允许用户删除链接,但我需要检查链接是否属于用户,这是我的表的工作方式:

links
----------------
id
category_id

links_categories
----------------
id
user_id

users
----------------
id

我这样定义我的关系:

class Link extends Eloquent
{
    public function category()
    {
        return ($this->belongsTo('LinkCategory', 'category_id', 'id')->with('categoryType'));
    }
}

class LinkCategory extends Eloquent
{
    public function links()
    {
        return ($this->hasMany('Link', 'category_id'));
    }

    public function user()
    {
        return ($this->belongsTo('User'));
    }
}

class User extends Eloquent implements UserInterface, RemindableInterface
{
    public function linkCategories()
    {
        return ($this->hasMany('LinkCategory')->with('links', 'categoryType'));
    }
}

他们是验证链接属于用户这一事实的简单方法吗?

谢谢。

【问题讨论】:

  • 试试这样的..$idsOfLinkCategories = $user->linkCategories()->lists('category_id'); return in_array($linkCategoryId,$idsOfLinkCategories);

标签: php validation laravel


【解决方案1】:

如果您想预先限制删除 - 例如,在链接列表中,您只想在属于他们的链接旁边向用户显示“删除”按钮 - 那么您可以查看@987654323 @ 在显示链接时反对Auth::user()->id。对于每个链接,user_id 可通过$link->category->user_id 访问,您可以在获取链接列表时使用->with('category') 预先加载。

或者(或者,另外)您可以设置一个模型事件侦听器,该侦听器将在删除链接时执行此验证。在您的 links 模型中,设置您的侦听器:

public static function boot()
{
    parent::boot();

    static::deleting(function($link)
    {
        if ($link->category->user_id != Auth::user()->id) {
            Session::flash('error', 'delete_unauthorized');
            return false;
        }
    });
}

链接的deleting监听器会检查用户是否被授权删除链接,如果没有,它会返回false(防止删除发生)并发送错误代码到下一个请求,如果您需要向用户提供反馈,您可以随意处理。 http://driesvints.com/blog/using-laravel-4-model-events 是一个很好的使用模型事件的演练。

您可以使用模型观察器扩展此功能;见http://matthewhailwood.co.nz/laravel-model-validation-using-observers/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-28
    • 1970-01-01
    • 2014-10-28
    • 2018-12-31
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多