V
V
vlad31442019-03-31 21:44:43
Laravel
vlad3144, 2019-03-31 21:44:43

How to properly use middleware in Laravel?

For some reason, there was such an opinion, based on the video materials viewed and examples from the Internet, that middleware is used only to check user authentication and authorization.
Does it make sense, for example, to use middlaware to check the validity of the data passed from the form to the controller?
Help, please, to understand.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
J
jazzus, 2019-03-31
@vlad3144

Validation of form fields
You create a form.
Create a Request file.
You write the rules and messages there.
You connect in the controller, to the method where the post-request goes, and this file will validate the fields.
Middleware does not validate fields. Used to filter requests. For example, to allow access to certain routes only to users who meet the conditions. Plus to carry out actions in the course of check. For example, log out of blocked ones and redirect to the main one.

G
grinat, 2019-03-31
@grinat

No. Xs in laravel, but if there is mvc, then the request data is processed in the controller, and middlaware there will be what stands before your processing in the controller. That is, for example, authorization, in middlaware we check whether the user is authorized, if so, then we transfer the data further for processing to the controller. In practice, it makes sense to use them if, for example, an analyst came and said that if we are processing a vegetable, then we need to display a message to the person: you are a tomato, and you have a bunch of controller: potato controller, cabbage controller, looknotroller, etc., and instead of you in all of them insert the message you are a tomato, add middlaware and see if it is a vegetable in it, and if so, then display the message you are a tomato.

J
javanub, 2019-03-31
@javanub

For field validation, there is a validator
public function store(Request $request, StoreBlogTag $store)
{
$validate = Validator::make($request->all(), $store->rules(), $store->messages() );
if ($validate->fails()) {
return redirect('post/create')
->withErrors($validate)
->withInput();
};
$tag = Tag::firstOrCreate([
'title' => $request->input('title'),
'slug' => Str::slug($request->input('title'), '-') ,
]);
$tag->save();
return redirect()->back();
}

D
Danny Chase, 2019-04-01
@Dase23

Stop inflating controllers, let them perform their direct functions, write logic in service classes, write validation in requests, intermediaries cannot be used not only for authorization, according to best practice in Laravel, they are used to work with incoming http requests, check tokens, add and checks of special headers, redirects, logging, cors, etc., etc., that is, all the application logic that must work out before the business logic is executed

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question