-
-
Save nicoaudy/971a6ed1a37497cda609f18c291b0f2e to your computer and use it in GitHub Desktop.
Example of using A Laravel Controller to automatically handle validation exceptions and auth failures
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class BaseController extends Controller | |
{ | |
public function callAction($method, $params) | |
{ | |
$ajax = Request::isAjax(); | |
try { | |
return parent::callAction($method, $params); | |
} catch(ValidationException $exception) { | |
return $this->handleValidationException($exception, $ajax); | |
} catch(AuthException $exception) { | |
return $this->handleAuthException($exception, $ajax); | |
} | |
} | |
protected function handleValidationException(ValidationException $exception, $ajax = false) | |
{ | |
if($ajax) { | |
return Response::json(array('errors' => $exception->errors()), 422); | |
} else { | |
return Redirect::back()->withInput()->withErrors($exception->errors()); | |
} | |
} | |
protected function handleAuthException(AuthException $exception, $ajax = false) | |
{ | |
if(Request::isAjax()) { | |
return Response::json($exception->getMessage(), 403); | |
} else { | |
App::abort(403); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
public class FooController extends BaseController | |
{ | |
public function __construct(FooService $foos) | |
{ | |
$this->foos = $foos; | |
} | |
public function store() | |
{ | |
//throws ValidationException on failure | |
$foo = $this->foos->create(Input::all()); | |
return Redirect::route('foos.show', $foo->id); | |
} | |
public function update($id) | |
{ | |
//throws ValidationException on failure | |
//throws AuthException if the current user does not have access to a the relevant resource | |
$foo = $this->foos->findAndUpdate($id, Input::all()); | |
return Redirect::route('foos.show', $foo->id); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment