Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Access Control with Model Objects

I need to restrict the access to some parts of the application depending on the user logged in. I mean for example to let a user edit only its own posts on a blog application.

Is there a better approach than in every function of the controller, if the user is not the owner of the required post, redirect to some error page?

For example if my routes are /post/{post_id}/edit, /post/{post_id}/preview, /post/{post_id}/delete, can I somehow declare a general function in the PostController like:

if(Post::find($post_id)->user_id != Auth::user()->id){
    return View::make('access-error');
}

Thanks!

like image 624
Andreu Ramos Avatar asked May 28 '26 19:05

Andreu Ramos


1 Answers

In your controller you can do something like this:

public $check = ['edit', 'preview', 'delete'];

public function callAction($method, $parameters) {
    if(in_array($method, $this->check, true) && 
    $post_id = $parameters['post_id'] &&
    Post::find($post_id)->user_id != Auth::user()->id) {
        return View::make('access-error');
    }

    return parent::callAction($method, $parameters);
}