Laravel 5用户权限

时间:2016-07-04 16:16:32

标签: laravel authentication

我是laravel(5.2)的新手并且遵循了这个伟大的系列https://www.youtube.com/watch?v=Zxmf0n2sC1I&index=34&list=PLwAKR305CRO-Q90J---jXVzbOd4CDRbVx

有人可以指出我正确的方向如何设置注册用户只能编辑/删除他们的OWN帖子的身份验证。

例如:登录用户" A"不允许编辑用户B的帖子。

感谢您帮助我。

4 个答案:

答案 0 :(得分:1)

您可以使用ApiGuard。查看更多:https://github.com/chrisbjr/api-guard

答案 1 :(得分:1)

如果您的帖子表格有user_id,那么您可以检查该用户是否与登录用户相同。例如:

routes.php文件

Route:get('post/{id}/edit', PostsController@edit);

PostsController.php

class PostsController extends Controller{
    public function edit($id){
        $post = Post::findOrFail($id);
        if($post->user_id !== Auth::user()->id){
            abort(403);
        }
        return view('posts.edit', $post);
    }
}

编辑:已更新,包括评论中要求的索引方法。

routes.php文件

Route:get('posts', PostsController@index);
Route:get('post/{id}/edit', PostsController@edit);

PostsController.php

class PostsController extends Controller{

    public function index(){
        $posts = Post::all();
        return view('posts.index', $posts);
    }        

    public function edit($id){
        $post = Post::findOrFail($id);
        if($post->user_id !== Auth::user()->id){
            abort(403);
        }
        return view('posts.edit', $post);
    }

}

答案 2 :(得分:1)

大。这非常适合编辑。但是我的索引视图出现了问题(列出了所有帖子)。我的代码看起来像:

public function index($id)
{
    //create a var and store all blog posts from DB        
    $posts = Post::findOrFail($id);
    if($posts->id !== Auth::user()->id){
        abort(403, 'Access denied');
    }

    //return a view and pass in the above var
    return view('posts.index')->withPosts($posts);

}

我视图中的错误消息是:PostController.php第23行中的ErrorException: 缺少App \ Http \ Controllers \ PostController :: index()

的参数1

我不知道如何处理索引($ id),我从哪里获取id?

再次感谢

答案 3 :(得分:0)

我的帖子有一个user_id,然后您可以检查该用户是否与登录用户相同。代码将是

PostController.php

    class PostController extends Controller
{
public function getUpdatePost($post_id) {

        $post = Post::find($post_id);
        if($post->user_id !== Auth::user()->id){
            abort(403);
        }
        return view('posts.edit',['post' => $post]);
    }
}

,你的路线文件将是

Route::get('/post/{post_id}/edit', [
                'uses' => 'PostController@getUpdatePost',
                'as' => 'post.edit'
        ]);