Skip to content

Instantly share code, notes, and snippets.

@atrauzzi
Last active November 11, 2015 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save atrauzzi/3edc38d7a9c7c4bcdd2f to your computer and use it in GitHub Desktop.
Save atrauzzi/3edc38d7a9c7c4bcdd2f to your computer and use it in GitHub Desktop.
Some of the things I love about Laravel 5 request handling.
<?php
use Illuminate\Routing\Controller;
use Illuminate\Foundation\Http\FormRequest;
//
use Illuminate\Http\Request;
/**
*
* Keep in mind, this uses a lot of idiomatic PHP. Any variable can be used as a nullable type and null
* evaluates to false in PHP. So it allows for some nice shortcuts once in a while.
*
*/
class Sample extends Controller {
// If desired, you could also pre-empt this action with a filter/middleware at the routing level
// that requires authentication. Then the framework would return a 403 response without even
// needing to run the action.
// This offers up several advantages on the DRY front as well as reducing the overall amount of
// defensive code required. You only code for your "good scenario", the framework traps the rest!
public function me(Request $request) {
return new JsonResponse($request->user());
}
// Again, before the action is even run, the framework checks the criteria defined in $signupRequest
public function signup(SignupRequest $signupRequest, UserService $userService) {
$newUser = $userService->signup($signupRequest->only([
'alias',
'password',
'tagline',
]));
// Again, consider that the only way we could have hit this line is if everything
// succeeded. Minimal amount of code!
return new JsonResponse($user);
}
}
// Here's a sample form request class simulating what a user signup might look like.
class SignupRequest extends FormRequest {
// Input validation is run before anything else and ensures that the structure of the request
// is workable. An HTTP 422 is generated if any of these rules fail.
public function rules() {
return [
'alias' => 'required|min:4|unique:user',
'password' => 'required|confirmed',
'tagline' => 'min:10'
];
}
// This is a function that must return true in order to allow the request to continue.
// You can author complex custom algorithms to check the state of the request before
// any action that uses it is run.
// Notice that method injection is available here, so I am using a fictional BanService.
public function authorized(BanService $banService) {
return $banService->allowed($this->getClientIp());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment