S
S
suhuxa12017-10-15 12:39:30
Laravel
suhuxa1, 2017-10-15 12:39:30

How to find out the request method in laravel (if it is in the match route)?

Good afternoon!
Add this route:

Route::match(['get', 'post'], 'action', ['uses' => '[email protected]']);

Actually action can be any. If get request - then open page action. And if a post request means that the form on this page worked. Here's how to properly separate these 2 tasks? Am I doing the right thing at all by giving both methods to the same controller function? I used to write 2 different routes and functions in the controller for get and post, now I want to shorten it.
Thanks to!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2017-10-15
@suhuxa1

Am I doing the right thing at all by giving both methods to the same controller function?
If you need to distinguish between the type of request inside this method, then no, something is wrong with you.
Here's how to properly separate these 2 tasks?
Generate a resource controller using standard tools and see how it's done idiomatically. Yes, just add Route::resource(...)and call php artisan route:list, there the entire controller structure will be visible.
I used to write 2 different routes and functions in the controller for get and post, now I want to shorten it.
GET is the output of the form, POST is the processing of user input. This is a different logic, there is usually nothing in common in these methods, therefore, instead of "reduce" in this case, it is more correct to use "complicate your work" or "worse the code".
However, here is the answer directly to your question: this task is solved using the request object:
Route::match(['get', 'post'], 'test', function (\Illuminate\Http\Request $request) {
    return $request->method();
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question