0

I'm new to Laravel (we're using 5.0 at work). Right now, when we respond to an API request in a Controller, we are rewriting the same code over and over to respond to unauthorized actions. For example,

public function getUsers(){
  if (Entrust::can('users.view')){
    $users = Users::get();
    return response()->done($users, 200);
  } else {
    return response()->unauthorized('users.view');
  }
}

It gets more and more complicated if we have different permissions that can allow an API request to succeed.

I'd like to simply throw an exception of some sort if the user cannot perform the API request. For example,

public function getUsers(){
  require('users.view'); // throws an UnauthorizedException if current user doesn't have 'users.view' permission

  $users = User::get();
  return response()->done($users, 200);
}

public function someOtherMethod(){
  if (!Entrust::can('permission1') && !Entrust::can('permission2')){
    throw new UnauthorizedException(['permission1', 'permission2']);
  }

  // some other stuff
}

But I don't know what code calls the API function, nor where to wrap that call in a try/catch. It's easy enough to code the UnauthorizedException, and easy to transform it into json, but where do I put the handler? As I said, I'm new to Laravel, and I don't know how it handles these exceptions.

Ideally, whatever solution I find, I'd like to extend it to other exceptions so we can have consistent json responses based on common exceptions.

3
  • I'm just beginning to dig into Laravel 5, but I would look at Middleware if this is something that is being run on multiple routes. Commented May 16, 2015 at 22:22
  • This is exactly what I needed (I got it working). If you add an answer to this effect I'll accept it, and comment with the exact steps I took. Commented May 16, 2015 at 23:26
  • Done - glad you got it working! Commented May 17, 2015 at 16:04

1 Answer 1

2

Instead of repeating your code, take a look at implementing the authorization check with Middleware.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.