The POST method is not supported for this route. Supported methods: GET, HEAD. + Laravel - laravel

I am trying to update .
I am getting the error
The POST method is not supported for this route. Supported methods: GET, HEAD.
Following are the code
In Route
Route::post('editcountries','App\Http\Controllers\backend\admineditcountryController#editcountries');
In Controller
function editcountries(Request $request)
{
$country_en = $request->input('country_en');
$country_ar = $request->input('country_ar');
$id = $request->input('idd');
$cstatus = 1;
if (isset($request->status))
$cstatus = 1;
else
$cstatus = 0;
$isUpdateSuccess = country::where('id',$id)->update(['country_en'=> $country_en,
'country_ar'=> $country_ar,
'status' => $cstatus
]);
$this->clearToastr();
session()->put('updated','Information updated Successfully.');
return view('backend.adminaddcountry');
}
In blade
<form action="editcountries" method="POST" enctype="multipart/form-data">
#csrf
{{-- #method('PUT') --}}
{{-- <input type="hidden" name="_method" value="PUT">" --}}
<div class="input-style-1">
<label>Country Name in English </label>
<input type="text" name="country_en" placeholder="Country Name in English"
value='{{ $clist->country_en }}' required/>
</div>
<div class="input-style-1">
<label>Country Name in Arabic</label>
<input type="text" dir="rtl" name="country_ar" placeholder="اسم الدولة بالعربية" value='{{ $clist->country_ar }}' />
</div>
<!-- end input -->
<div class="form-check form-switch toggle-switch">
<input class="form-check-input" name="status" type="checkbox" id="toggleSwitch2" #if($clist->status==1)
checked=""
#else
#endif>
<label class="form-check-label" for="toggleSwitch2">Enable or disable the country.</label>
</div>
<input type="hidden" id="idd" name="idd" value="{{ $clist->id }}" />
<br>
<button class="main-btn primary-btn btn-hover text-center">Update</button>
</form>
I tried using
#method('PUT')
but then getting error
The PUT method is not supported for this route. Supported methods: GET, HEAD.
Please help
I tried putting
I tried using
#method('PUT')
but then getting error
The PUT method is not supported for this route. Supported methods: GET, HEAD.
Please help

You might have your routes cached, you can try running the following commands in the terminal:
php artisan route:clear
php artisan route:cache
You should get rid of the code you added making it a put request, unless that is what you want. If you want it to be a PUT route you need to use:
Route::put
Otherwise if you still can't figure it out, go through your routes file and check for any other routes that match "editcountries". Sometimes the order you put the routes can cause conflicts with other routes, like a resource route for example. However I would say if you get rid of the PUT code in the blade file, and run the route cache commands I provided, you should have it working with the post route.

How to Debug:
Run: php artisan route::list --path admineditcountryController
If you do not see your controller in the output run php artisan route:clear
I would not recommend running route:cache as you'll have to continuously route:clear any time you change/add/remove routes — set that up in your CI to only run in PROD. In fact — you should just run php artisan optimize in production and it'll do a bunch of fancy performance Laravel magic for ya (further reading)
Other Improvements (PR Comments)
1. Follow PSR-2 File/Class/Namespace NAming
Aside, make sure your folder & namespaces are following PSR-2 (CamelCase)
App\Http\Controllers\backend\admineditcountryController
# should be
App\Http\Controllers\Backend\AdminEditCountryController
# even better (Namespaced)
App\Http\Controllers\Backend\Admin\CountryController
2. Reference controllers using an import
This is a bit cleaner (PHP 7+) + try utilizing Route::resource + Laravel Action Verbs as controller function names docs
use App\Http\Controllers\Backend\AdminEditCountryController;
/* Simplified - Best practice: use dashes as URL delimiters '-' */
Route::post('edit-countries', AdminEditCountryController::class . '#editcountries');
/* PRO VERSION */
Route::group('admin')->prefix('admin')->name('admin.')->group( function () {
// AdminEditCountryController#update()
Route::resource('country', Admin\CountryController::class)->only(['update']);
});
3. Extra Credit
Try generating your controllers (benefits from PSR-2 compliant namespace & folder layouts):
php artisan make:controller Admin\CountryController --resource

I resolved it.
Route
Route::post('/editcountries','App\Http\Controllers\backend\admineditcountryController#editcountries');
Controller
function editcountries(Request $request)
{
$country_en = $request->input('country_en');
$country_ar = $request->input('country_ar');
$id = $request->input('idd');
$cstatus = 1;
if (isset($request->status))
$cstatus = 1;
else
$cstatus = 0;
$isUpdateSuccess = country::where('id',$id)->update(['country_en'=> $country_en,
'country_ar'=> $country_ar,
'status' => $cstatus
]);
$this->clearToastr();
session()->put('updated','Information updated Successfully.');
$data = country::where('id', '=', $id)->first();
return view('backend.admineditcountry',['clist'=>$data]);
}
Blade
<form action="/editcountries" method="POST" enctype="multipart/form-data">
#csrf
<div class="input-style-1">
<label>Country Name in English </label>
<input type="text" name="country_en" placeholder="Country Name in English"
value='{{ $clist->country_en }}' required/>
</div>
<div class="input-style-1">
<label>Country Name in Arabic</label>
<input type="text" dir="rtl" name="country_ar" placeholder="اسم الدولة بالعربية" value='{{ $clist->country_ar }}' />
</div>
<!-- end input -->
<div class="form-check form-switch toggle-switch">
<input class="form-check-input" name="status" type="checkbox" id="toggleSwitch2" #if($clist->status==1)
checked=""
#else
#endif>
<label class="form-check-label" for="toggleSwitch2">Enable or disable the country.</label>
</div>
<input type="hidden" id="idd" name="idd" value="{{ $clist->id }}" />
<br>
<button class="main-btn primary-btn btn-hover text-center">Update</button>
</form>

Related

Error message "The GET method is not supported for this route. Supported methods: POST." in laravel 8

Following is my controller. Method ProjectsView is to view all the listings. The second method BackendProjectSearch is for searching of projects. The first page of search result is displayed properly, but when we click on next page it gives the error "The GET method is not supported for this route. Supported methods: POST."
What should I do ?
public function ProjectsView(){
$projects = projects::orderBy('id','ASC')->paginate(15);
return view('backend.projects.projects_view',compact('projects')); }
public function BackendProjectSearch(Request $request){
$request->validate(["search" => "required"]);
$item = $request->search;
$projects = Projects::where('project_name','LIKE',"%$item%")->paginate(15);
return view('backend.projects.projects_view',compact('projects')); }
Following are the routes for both the methods :
Route::post('/backend/project/search', [ProjectsController::class, 'BackendProjectSearch'])->name('backend.project.search');
Route::get('/view', [ProjectsController::class, 'projectsView'])->name('projects.view');
View code :
<div class="col-md-8">
<div class="header-navsearch">
<form class="form-inline mr-auto" method="post" action="{{route('backend.project.search')}}">
#csrf
<div class="nav-search">
<input type="search" name="search" class="form-control header-search" placeholder="Search projects…" aria-label="Search">
<button class="btn btn-primary" type="submit"><i class="fa fa-search"></i></button>
</div>
</form>
</div>
</div>
The route for this request should be post, not get.
Example
Route::post(-----);
Also, make sure to insert a CSRF token while making the request
it means you now cannot do something like the following.
Instead, you have to do something like...
<form action="{{ route('example') }}" method="POST">
#csrf {{-- According to the version of laravel --}}
{{-- Your other codes --}}
<button type="submit" class="">Submit</button>
</form>
You have to use the below code
return redirect()->route('projects.view')->with(['projects' => $projects]);
Your route might be little change
Route::get('/view/{projects?}', [ProjectsController::class, 'projectsView'])->name('projects.view');
and In your controller, you have to change function like this
public function ProjectsView($projects = null){
if($projects!=null){
return view('backend.projects.projects_view',compact('projects'));
}
else{
$projects = projects::orderBy('id','ASC')->paginate(15);
return view('backend.projects.projects_view',compact('projects'));
}

Laravel - CSRF Token Mismatch - Header Token gets regenerated

I'm struggeling the last 2 weeks on the following problem:
First of all my problem only occours when I try to deploy my current Laravel (6.11) project on the live server. On my Localhost everything works fine.
In every FORM I used the #csrf tag to set the token as well as the meta tag in the head section of my page. If I search into the developer tool in Chrome the tokens in head and form match perfectly. When the POST request gets sent I get an 419 Page Expired error. I figured out that the HEAD token gets recreated on each request so a token mismatch occours.
I already tried the following things:
Diffrent syntax of the csrf tag
I excepted all FORMS in the VerifyCsrfToken.php - these ended up in a redirect to my index.php without submited form
I checked all Laravel config settings which were recommended in diffrent Forum Posts
I tried a empty laravel installation with a basic login setup on my server - This worked
I currently work with git. On the a previous commit version (16th of december) which I uploaded to my server on that exact Date I had no problem at all but when I tried to reupload the exact same git commit date, the same problem happens.
Greatings Max
If you need any code I'll upload here.
Controller:
function fakeAuthentifizierung(Request $request){
$username = $request->input('benutzernameLogin');
$password = $request->input('passwortLogin');
session(['key' => 'mt171043']);
session(['eingeloggt' => true]);
/*****
* ABFRAGE ADMINRECHTE
* BITTE DIESEN TEIL SPÄTER IN ECHTE AUTHENTIFIZIERUNG ÜBERNEHMEN
*
*/
$admin = false;
// SPÄTER BENUTZERID AUS LOGIN SESSION ÜBERGEBEN
// astmedin5 als TESTZWECK
$rechte = Benutzer::getBenutzerBerechtigung("astmedin5");
//Berechtigung Abfragen
if($rechte->name != 'Student' && 'Lehrbeauftragter'){
session(['admin' => true]);
}else{
session(['admin' => false]);
}
/***
*
* ABFRAGE ENDE
*/
return redirect(route('index',app()->getlocale()));
}
View:
<form method="POST" action="{{ action('LoginController#FakeAuthentifizierung', app()->getLocale()) }}">
#csrf
<h1>{{ __('Login') }}</h1>
<label class="col" for="benutzernameLogin">{{ __('Benutzername') }}</label>
<input name="benutzernameLogin" id="benutzernameLogin" class="inputLogin col mb-4" type="text"
aria-label="Text input with checkbox" placeholder="{{ __('Benutzername') }}" required>
<label class="col" for="passwortLogin">{{ __('Passwort') }}</label>
<input name="passwortLogin" id="passwortLogin" class="inputLogin col mb-4" type="password"
aria-label="Text input with checkbox" placeholder="{{ __('Passwort') }}" required>
<div class="col-8 float-left">
<input id="checkboxPasswortAnzeigen" type="checkbox">
<label for="checkboxPasswortAnzeigen">{{ __('Passwort anzeigen') }}</label>
</div>
<button type="submit" class="btn-slash col-3 inverted fontLight float-right">{{ __('Login') }}</button>
</form>

Laravel custom login is failing for the first time with "route [login] not defined" error. Working fine in second attempt

I'm setting up my custom authentication system in my Laravel app. I've deleted all the default auth controllers and not using make::auth. And my auth is working properly. My main problem is that when I tried to log in for the first time, it's failing with "Route [login] not defined" error, but in second attempt, it's working properly. And if I repeat the process, it's continuing again and again like the first two attempt. Actually, I've never used login route anywhere.
Here is my form:
<form action="{{ url('/log-in') }}" method="POST">
#csrf
<input type="text" name="phone" placeholder="Telefon" class="form-control input-phone">
<input type="password" name="password" placeholder="Parol" class="form-control">
<button type="submit" class="btn">Kirish</button>
</form>
Here is my route:
Route::post('/log-in', 'AuthController#login');
Here is my controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use App\User;
class AuthController extends Controller
{
public function login(Request $request) {
// Get current user.
$user = User::where('phone', $request->phone)
->first();
if ( Hash::check($request->password, $user['password']) ) {
Auth::login($user, true);
Auth::logoutOtherDevices($request->password);
return redirect()->back();
}
}
}
Use for route.
Route::post('/log-in', 'AuthController#login')->name('login');
Use your form.
<form action="{{ route('login') }}" method="POST">
#csrf
<input type="text" name="phone" placeholder="Telefon" class="form-control input-phone">
<input type="password" name="password" placeholder="Parol" class="form-control">
<button type="submit" class="btn">Kirish</button>
</form>
This is a tricky and annoying problem. you need to change your return from return redirect()->back(); to loading 1 known blade or a known redirect. Sometimes at login your route fails to set a back redirect. so you can try to set a return view() or a return to a known url. So for example if the login is success return to index , if not load error page.
Hope this helps

Getting a Forbidden when trying to access my controller

I've created a form that when submitted it needs to go to a controller function.
At the moment when I'm submitting my form I keep getting
Forbidden
You don't have permission to access /client_area/shop/payment-gateway on this server.
Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request.
I've done forms before but this is the first time this has happened to me and it has me stumped.
my form
<div class="payment-form">
<form action="{{ route('payment.gateway') }}" method="POST">
#csrf
<input type="hidden" name="return_url" value="{{ route('payment.success') }}">
<input type="hidden" name="cancel_url" value="{{ route('payment.cancel') }}">
<input type="hidden" name="m_payment_id" value="{{ $invoice_number }}">
<input type="hidden" name="amount" class="completePrice" value="">
<input type="hidden" name="item_name" value="Test Item">
<input type="hidden" name="item_description" value="A test product">
<input type="hidden" name="delivery_collection" class="delivery_collection" value="">
<input type="hidden" name="delivery_fee" class="delivery_fee" value="{{ $delivery }}">
<input type="hidden" name="delivery_address" class="delivery_address" value="{{ $address }}">
<button type="submit" class="btn btn-success float-right confirm-order">
Confirm Order
</button>
</form>
</div>
my routes
Route::group(['middleware' => ['web', 'auth']], function(){
Route::get('/account/dashboard', 'UsersController#accountDashboard')->name('account.dashboard');
Route::get('/account/details', 'UsersController#personalDetails')->name('account.details');
Route::get('/account/track-orders', 'UsersController#trackOrders')->name('account.track-orders');
Route::get('/account/invoices', 'UsersController#invoices')->name('account.invoices');
Route::get('/account/address', 'UsersController#addressesIndex')->name('account.addresses.index');
Route::get('/account/sort-orders', 'UsersController#sortOrders')->name('account.sort-orders');
Route::get('/account/order-details/{invoice_number}', 'UsersController#orderDetails')->name('account.order-details');
Route::get('/account/invoice-pdf/{id}', 'UsersController#invoicesPdf')->name('account.invoices.pdf');
Route::get('/account/create-address', 'UsersController#createAddress')->name('account.create.address');
Route::get('/account/edit-address/{id}', 'UsersController#editAddress')->name('account.edit.address');
Route::get('/delivery-confirmation', 'PublicController#deliveryConfirmation')->name('cart.deliveryConfirmation');
Route::get('/account/edit-delivery-address/{id}', 'UsersController#editDeliveryAddress')->name('account.edit.delivery.address');
Route::get('/payment-success', 'PublicController#successPayment')->name('payment.success');
Route::get('/payment-cancel', 'PublicController#cancelPayment')->name('payment.cancel');
Route::post('/account/personal-details', 'UsersController#postPersonalDetails')->name('post.personal-details');
Route::post('/account/business-details', 'UsersController#postBusinessDetails')->name('post.business-details');
Route::post('/account/addresses-radio/{id}', 'UsersController#postAddressesRadio')->name('account.post.addresses.radio');
Route::post('/account/create-address', 'UsersController#postAddress')->name('account.post.address');
Route::post('/account/edit-address/{id}', 'UsersController#updateAddress')->name('account.update.address');
Route::post('/payment-gateway', 'PublicController#paymentGateway')->name('payment.gateway');
Route::delete('/account/delete-delivery-address/{id}', 'UsersController#deleteDeliveryAddress')->name('account.delete.delivery.address');
});
I've only done a dd() to make sure I hit the right function
public function paymentGateway()
{
dd('this is a payment gateway');
}
My Auth Middleware
<?php
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* #param \Illuminate\Http\Request $request
* #return string
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
}
This is what I see when I go through the network tab. Because it's alot of images I thought it would be better to have it as a link then just pasting the images here.
Image 1
Image 2
Image 3
Image 4
Image 5
Image 6
Image 7
Image 8
Laravel comes with Cross Site Request Forgery protection. You need to also pass a field named csrf-token as stated here in the documentation.
https://laravel.com/docs/5.8/csrf#csrf-x-csrf-token
If you do not want this protection you must include the route in the VerifyCsrfToken Middleware to exclude the checking.
https://laravel.com/docs/5.8/csrf#csrf-excluding-uris
Try this to see if that solves your issue.

laravel 5.5 | old() empty in view unless $request->flash() used

I've run into an odd issue where the helper function old() always returns null in a blade view unless $request->flash() is used prior to loading the view. I have never had to do this when using laravel in the past. Did something change or is there something that I have forgotten to set/configure. Below is a simple example of the behavior:
web.php
Route::get('/test', function(){
return view('testView');
});
Route::post('/test', function(Illuminate\Http\Request $request){
$request->flash(); // if uncommented old() works, if commented old() does not work
return view('testView');
});
form in testView.blade.php
<form action="/test" method="POST">
{{csrf_field()}}
<input type="hidden" name="test001" value="001"/>
<input type="hidden" name="test002" value="002"/>
<div class="">
{{old('test001')}}
<br/>
{{old('test002')}}
</div>
<button type="submit">GO</button>
</form>
after form submitted without $request->flash()
after form submitted with $request->flash()
EDIT
Thinking this might have something to do with using a single route name for both post and get methods, the form was changed so to submit via get, and the issue persists. For example:
web.php
Route::get('/test', function(function(Illuminate\Http\Request $request){
return view('testView');
});
form in testView.blade.php
<form action="/test" method="GET">
<input type="hidden" name="test001" value="001"/>
<input type="hidden" name="test002" value="002"/>
<div class="">
{{old('test001')}}
<br/>
{{old('test002')}}
</div>
<button type="submit">GO</button>
</form>
Use redirect back() instead of loading view directly in a post method.
return redirect()->back()->withInput();
You need to flash request data to put old input into session, otherwise old() will return empty result. See official doc here.

Resources