Cleaning Up Laravel Controllers
- 2021年11月25日
- Web Service
Introduction
Controllers play a huge role in any MVC (model view controller) based project. They’re effectively the “glue” that takes a user’s request, performs some type of logic, and then returns a response.
The Problem with Bloated Controllers
Bloated controllers can cause several problems for developers. They can:
1. Make it hard to track down a particular piece of code or functionality.
2. Make it difficult to spot the exact location of a bug.
3. Make it harder to write tests for more complex requests.
The Bloated Controller
For this blog, I am going to use an example UserController
:
class UserController extends Controller { public function store(Request $request): RedirectResponse { $this->authorize('create', User::class); $request->validate([ 'name' => 'string|required|max:50', 'email' => 'email|required|unique:users', 'password' => 'string|required|confirmed', ]); $user = User::create([ 'name' => $request->name, 'email' => $request->email, 'password' => $request->password, ]); $user->generateAvatar(); $this->dispatch(RegisterUserToNewsletter::class); return redirect(route('users.index')); } public function unsubscribe(User $user): RedirectResponse { $user->unsubscribeFromNewsletter(); return redirect(route('users.index')); } } 1. Lift Validation and Authorization into Form Requests One of the first things that we can do with the controller is to lift any validation and authorization out of the controller and into a form request class. We’ll use the following Artisan command to create a new form request: php artisan make:request StoreUserRequest The above command will have created a new app/Http/Requests/StoreUserRequest.php class that looks like this: class StoreUserRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return false; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ // ]; } } We can use the authorize() method to determine if the user should be allowed to carry out the request. The method should return true if they can and false if they cannot. We can also use the rules() method to specify any validation rules that should be run on the request body. class StoreUserRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize(): bool { return Gate::allows('create', User::class); } /** * Get the validation rules that apply to the request. * * @return array */ public function rules(): array { return [ 'name' => 'string|required|max:50', 'email' => 'email|required|unique:users', 'password' => 'string|required|confirmed', ]; } } Our controller should now also look like this: class UserController extends Controller { public function store(StoreUserRequest $request): RedirectResponse { $user = User::create([ 'name' => $request->name, 'email' => $request->email, 'password' => $request->password, ]); $user->generateAvatar(); $this->dispatch(RegisterUserToNewsletter::class); return redirect(route('users.index')); } public function unsubscribe(User $user): RedirectResponse { $user->unsubscribeFromNewsletter(); return redirect(route('users.index')); } } 2. Move Common Logic into Actions or Services Another step that we could take to clean up the store() method could be to move out our "business logic" into a separate action or service class. class StoreUserAction { public function execute(Request $request): void { $user = User::create([ 'name' => $request->name, 'email' => $request->email, 'password' => $request->password, ]); $user->generateAvatar(); $this->dispatch(RegisterUserToNewsletter::class); } } Now we can update our controller to use the action: class UserController extends Controller { public function store(StoreUserRequest $request, StoreUserAction $storeUserAction): RedirectResponse { $storeUserAction->execute($request); return redirect(route('users.index')); } public function unsubscribe(User $user): RedirectResponse { $user->unsubscribeFromNewsletter(); return redirect(route('users.index')); } } 3. Use Resource or Single-use Controllers A great way of keeping controllers clean is to ensure that they are either “ resource controllers” or “ single-use controllers”. A resource controller is a controller that provides functionality based around a particular resource. So, in our case, our resource is the User model and we want to be able to perform all CRUD (create, update, update, delete) operations on this model. A resource controller typically contains index(), create(), store(), show(), edit(), update() and destroy() methods. A single-use controller is a controller that only has one public __invoke() method. These are really useful if you have a controller that doesn't really fit into one of the RESTful methods that we have in our resource controllers. So let’s create a new controller using the following Artisan command: php artisan make:controller UnsubscribeUserController -i Notice how we passed -i to the command so that the new controller will be an invokable, single-use controller. We should now have a controller that looks like this: class UnsubscribeUserController extends Controller { public function __invoke(Request $request) { // } } We can now move our method’s code over and delete the unsubscribe method from our old controller: class UnsubscribeUserController extends Controller { public function __invoke(Request $request): RedirectResponse { $user->unsubscribeFromNewsletter(); return redirect(route('users.index')); } } Conclusion Hopefully this article has given you an insight into the different types of things you can do to clean up your controllers in your Laravel projects. Tsuki
tsuki at 2021年11月25日 10:00:00