Laravel 5.1使用中间件保护带有所有权的路由


Laravel 5.1 protecting routes with ownership using middleware

我正在尝试学习Laravel,但不太明白如何才能以最好的方式完成任务。

的场景中,

一个用户(user_id 5)可以创建一个id为3的待办事项列表(todo_id 3),每个列表都在自己的模型中,因此用户模型和待办事项模型。我正在检查他们是否创建了todo通过传入方法,

public function show($id)
{
    TodoList::where('id',$id)->where('user_id', auth::id())->firstOrFail();
    return 'ok';
}

所以,我认为有可能过滤所有这些,使用中间件。我有更多的模型,需要相同的行动,所以用户2,不能更改/编辑用户5等的todo_list。这需要附加到所有方法上,以阻止它们的访问。显示、查看、删除等

有没有办法做到这一点,所以我不必为每个模型创建一个新的中间件?

Laravel Eloquent为您提供了Query Scopes,这可能是您正在寻找的。

你的模型:

class TodoList extends Model {
    public function scopeFiltered($query, $id, $user_id)
    {
        return $query->where('id',$id)->where('user_id', $user_id);
    }
}
调用:

TodoList::filtered($id, Auth::user()->id)
   ->get();