A
A
Andrey Skripnik2020-07-21 11:08:33
Laravel
Andrey Skripnik, 2020-07-21 11:08:33

How to call a method in FormRequest constructor?

Good day! I decided to put in FormRequest, in addition to data validation, all the logic for accessing the action in the controller (it seems like a good practice to make controllers thin). I also came up with the idea to store frequently used variables, model instances, etc. in the request.
Created an abstract class, inheriting from FormRequest, created an abstract setProperties method in it. Now, in each individual request, I can describe in advance all the necessary access logic in the authorize () method, and assign all the necessary data to properties through the setProperties () method.
However, I ran into a problem: it is necessary to add the setProperties () method to the request constructor so that the data is assigned and available through the request in the controller, but a direct addition to __construct causes only a 500 error (Server Error).

Can you please tell me how to implement this correctly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jazzus, 2020-07-21
@andreskrip

It is better to make thin not only controllers, but also form requests. And any other classes. To do this, everyone must perform their function. For example, authorization in Laravel is handled by authorization policies . In addition to the cleanliness of the code and the absence of bicycles, the access logic in policies can be used throughout the application. Like $user->can('view', $post) etc.

came up with the idea to store frequently used variables in the request

If you want to take out some logic from the controller somewhere, it is better to use your service classes, and not the first Laravel classes that come across.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question