How to use Basic Routing methods in Laravel? - php

I have get some documents from Laravel Documentation.But i can't get details clearly from that. There are lot of routing methods and how to use that for my requirements? Commonly most people are using this, but what are the other routing methods?
Route::get()
Route::post()
How to pass the message or values through this Routing? Using Controller like this is a only way?
Route::get('/app', 'AppController#index');

Types of Routing in Laravel
There are some Routing methods in Laravel, There are
1. Basic GET Route
GET is the method which is used to retrieve a resource. In this example, we are simply getting the user route requirements then return the message to him.
Route::get('/home', function() { return 'This is Home'; });
2. Basic POST Route
To make a POST request, you can simply use the post(); method, that means when your are submitting a Form using action="myForm" method="POST", then you want to catch the POST response using this POST route.
Route::post('/myForm', function() {return 'Your Form has posted '; });
3. Registering A Route For Multiple Verbs
Here you can retrieve GET request and POST requests in one route. MATCH will get that request here,
Route::match(array('GET', 'POST'), '/home', function() { return 'GET & POST'; });
4. Any HTTP Verb
Registering A Route Responding To Any HTTP Verb. This will catch all the request from your URL according to the parameters.
Route::any('/home', function() { return 'Hello World'; });
Usage of Routing in Laravel
When your are Using the Route::, Here you can manage your controller functions and views as follows,
1. Simple Message Return
You can return a simple message which will display in the webpage when user request that URL.
Route::get('/home', function(){return 'You Are Requesting Home';});
2. Return a View
You can return a View which will display in the webpage when user request that URL
// show a static view for the home page (app/views/home.blade.php)
Route::get('/home', function()
{
return View::make('home');
});
3. Request a Controller Function
You can call a function from the Controller when user request that URL
// call a index function from HomeController (app/Http/Controllers)
Route::get('/home', 'HomeController#index');
4. Catch a value from URL
You can catch a value from requested URL then pass that value to a function from Controller. Example : If you call public/home/1452 then value 1452 will be cached and will pass to the controller
// call a show function from HomeController (app/Http/Controllers)
Route::get('/home/{id}', 'HomeController#show');

You can get help about routing from Laravel.
There are 4 methods ofform data sending that you must know --
Route::get for <form method="GET">
Route::post for <form method="POST">
Route::put for <form method="PUT"> -- This one is for updating your database, I recommend you to use laravelcollective/html, like this -- {!! Form::open(['method' => 'PUT']) !!}, but in your web browser you can find the method as POST only
Route::delete for <form method="DELETE"> -- This one is for deleteing a field in your database, I recommend you to use laravelcollective/html, like this -- {!! Form::open(['method' => 'DELETE']) !!}, but in your web browser you can find the method as POST only
There are many much you have to know about Laravel Routing, like CRUD, etc.

Related

redirect to a route using post method

i've registered a post route and set the "auth" middleware on it,everything is working properly but at the last step when i want to redirect to my registered route after authentication,an error occurred, it seems redirect() helper function uses GET method by default,but my route supports POST method.is there any way to use redirect() with POST method?!!
Route::post('match', 'HomeController#match')->name('match')->middleware('auth');
and inside my LoginController:
if ($is_match==='comes_from_match') {
return redirect()->route('match');
}else{
return redirect()->route('dashboard');
}
this leads to the following error:
"The GET method is not supported for this route. Supported methods: POST."
Try the following:
You can use any instead of post it works for both get and post.
Route::any('match', 'HomeController#match')->name('match')->middleware('auth');
As per latest Laravel documentation:
Sometimes you may need to register a route that responds to multiple HTTP verbs. You may do so using the match method. Or, you may even register a route that responds to all HTTP verbs using the any method:
You can use match or any method:
Route::match(['get', 'post'], '/', function () {
//
});
Route::any('/', function () {
//
});
Reference:
Laravel -> Routing -> Basic Routing

Laravel error upon submitting a form: MethodNotAllowedHttpException in RouteCollection.php line 218. What could this be due to?

There is a form in my view, from where, on clicking submit, data is taken to ajax script which is supposed to invoke the controllers specified in the post routes in routes.php. The controllers are expected to process the received data and throw the result back to the view. Why is this error occurring immediately after submitting the form and things aren't working as expected>
Check your routes.php file. Make sure that the method your using corresponds with what you have allowed.
Here is the laravel documenation for routes
For example, if your request is a GET request, the call should look like this in the routes file:
Route::get('/test-get-url', function () {
// Matches The "/test-get-url" URL using a GET method
});
And for post
Route::post('/test-post-url', function () {
// Matches The "/test-post-url" URL using a POST method
});
Go to terminal/cmd..whichever you using and type
php artisan route:list
this will list all your routes and check at what route your is being submitted.Note the corresponding method to be used in the Method column and use that method while submitting form.I'm assuming it's PUT method(which is most likely).Ex--
Use method attribute if you're using simple HTML code like--
<form action="{{route='..'}}" method="PUT">
or if you're using form helper then use--
{!! Form::open($post, ['route' => ['..'], 'method' => 'PUT']) !!}
Go to your route.php file and check
Route::get('someroute',['uses'=>'somecontroller#function_get','as'=>'some_get']);
Route::post('someroute',['uses'=>'somecontroller#funtion_post','as'=>'some_post']);
make sure if your are using (as) in you routes its different and also where you use your ajax you properly define your route where you want to post your form data and it's type is same as you mention in routes and one more thing check you properly use (;) in your code
hope this will help you fell free to ask your query

GET and POST controller for one route in Laravel

I want to have one route rule for both GET and POST methods that redirect to one controller. Problem is GET doesn't require any parameters (it returns a view) but POST will have some parameters that are sent through a form.
In ASP.NET MVC5 I do it with one route rule and two controller methods with the same name but one of them (the POST method) has a [HttpPost] attribute and the parameters it needs while the GET method doesn't have any parameter or attribute.
How does one implement something like that in Laravel 5.x?
This is the possible controller:
public function convertUrl($somedataforpost)
{
if(Request::isMethod('get'))
{
// return a view
}
if(Request::isMethod('post'))
{
// do something with POST data
}
}
This is an example of how you would implement the rule:
Route::match(['get', 'post'], 'order/{invoice}/confirm', ['uses' => 'OrderController#paymentConfirmation', 'as' => 'order.payment.confirmation']);

Laravel. Redirect intended to post method

I'm using laravel 5 and this is my problem. User fill in form X and if he isin't logged in, he gets redirected to fill in more fields form OR he gets possibility to log in. Everything works just fine, if user fill in additional fields, but if he login, laravel redirects user to form X with GET method instead of POST.
This is how my middleware redirect looks like:
return redirect()->guest('user/additional-fields');
This redirect appears on successfull log in:
return redirect()->intended();
So on redirect intended i get error
MethodNotAllowedHttpException. URL is correct which is defined as POST method. What am I missing here? Why does laravel redirects intended as GET method? How could I solve this problem? Thanks!
EDIT:
Route::post('/user/log-in-post', ['as' => 'user-log-in-post', 'uses' => 'UserController#postUserLogIn']);
This is my route, I hope this is one you need.
You can use a named route to solve this issue:
Lets make a named route like this:
For Get
Route::get('user/additional-fields',array(
'uses' => 'UserController#getAdditionalFields',
'as' => 'user.getAdditionalFields'
));
For post
Route::post('user/additional-fields',array(
'uses' => 'UserController#postAdditionalFields',
'as' => 'user.postAdditionalFields'
));
So we can now ensure Laravel uses the right route by doing this
return redirect()->guest(route('user.getAdditionalFields'));
Also note that its not possible to redirect a POST because Laravel expects form to be submitted. SO you can't do this:
return redirect()->guest(route('user.postAdditionalFields'));
except you use something like cURL or GuzzleHttp simulate a post request
You have to trick Laravel router by passing an "_method" the inputs.
The best way I found is by adding tricking and rewriting the Authenticate middleware
You have to rewrite the handle method to allow your redirection with your new input.
redirect()->guest('your/path')->with('_method', session('url.entended.method', 'GET'));
When you want to redirect to a route using another method than GET, simply do a Session::flash('url.entended.method', 'YOUR_METHOD').
Tell me if it do the trick
Very Simple Approach for Post method Route form Controller.
The idea behind this is, every Route always calls the Action method of a Controller. so that in that case you can directly call that method in place of Redirect action performed.
check a code sample of XYZController
$registration = Registration::find($req->regId);
$registration->update([ 'STEP_COMPLETED' => 5]); // Step 5 completed.
# Call Post Method Route
return $this->admissionFinish($req);
Note that $req should have all parameter that required in next
action Method.
change the below code in app\exceptions\handler.php
use Exception;
use Request;
use Illuminate\Auth\AuthenticationException;
use Response;
protected function unauthenticated($request,AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
//return redirect()->guest(route('login'));
return redirect()->guest('http://127.0.0.1:8000/api/signinnew'); // change this part to your login router
}
And in routes(i.e api.php):
Route::Any('signinnew', [UserLogonController::class, 'signinNew']);
This will work in laravel 8x

Laravel3: How can I forward post methods to action of controller?

Route::get('admin/user/add', function()
{
if (!Input::has('submit'))
return View::make('theme-admin.user_add');
else
Redirect::to('admin#user_add_process');
});
Normal GET request to admin/user/add shows the register form. However, when the form is submitted, I have to redirect it to action_user_add_process() function of Admin controller so I can save values to database.
The solution above doesn't work and I get 404's.
I call form action like this:
action="{{ URL::to('admin/user/add') }}">
How can I solve this issue?
Ps. If there is a shorter way to achieve this, let me know!
You need to specify that you are redirecting to a controller action using the to_action() method of Redirect.
return Redirect::to_action('admin#user_add_process');
Alternatively, you could just use this URL that doesnt even use the route you created making the if/else irrelevant.
{{ URL::to_action('admin#user_add_process') }}
On a third note, keeping your routes clean makes maintainence alot easier moving forward. As routes use a restful approach, take advantage of it. Using the same URL you can create and return the View with a GET request and submit forms with a POST request.
Route::get('admin/user/add', function() { ... }
Route::post('admin/user/add', function() { ... }
You can also have your routes automatically use a controller action like this:
Route::post('admin/user/add', 'admin#user_add_process');

Categories