POST call's are randomly called as GET (Symofny 2.8) - php

Error! Uncaught PHP Exception Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException: "No route found for "GET /admin/.../details/save": Method Not Allowed (Allow: POST)" at /.../vendor/symfony/symfony/src/Symfony/Component/HttpKernel/EventListener/RouterListener.php line 180
This error is simple, a url has been triggered not via POST. The problem I have is that, this route is never called with GET.
<form method="POST" action="{{ path('...', {'id': id}) }}">
{{ form_widget(form._token) }}
{{ form_widget(form.id) }}
<div class="form-group">
<label class="col-lg-2 control-label">Password</label>
<div class="input-group col-lg-10">
{{form_widget(form.password, {'attr':{'class': 'form-control'} })}}
{{ form_widget(form.random) }} Random
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label"></label>
{{ form_widget(form.notify) }} Notify user?
</div>
<div class="form-group">
<label class="col-lg-2 control-label"></label>
<div class="input-group col-lg-10">
<button type="submit" class="btn btn-primary btn-lg" style="width: 33%;">Save</button>
</div>
</div>
</form>
The problem continues overall in the project. Ajax call's to search are triggered with GET and I can't figure out where the error comes from. No js errors connected to this issue (checked with sentry). Any idea?
More info from emails:
Message:
Uncaught PHP Exception Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException: "No route found for "GET /api-v2/search": Method Not Allowed (Allow: POST)" at /.../vendor/symfony/symfony/src/Symfony/Component/HttpKernel/EventListener/RouterListener.php line 180
Time:
2017-06-08 17:54:31
Channel:
request
Context:
exception:
{
"class": "Symfony\\Component\\HttpKernel\\Exception\\MethodNotAllowedHttpException",
"message": "No route found for \"GET /api-v2/search\": Method Not Allowed (Allow: POST)",
"code": 0,
"file": "/.../vendor/symfony/symfony/src/Symfony/Component/HttpKernel/EventListener/RouterListener.php:180",
"trace": [
"{\"function\":\"onKernelRequest\",\"class\":\"Symfony\\\\Component\\\\HttpKernel\\\\EventListener\\\\RouterListener\",\"type\":\"->\",\"args\":[\"[object] (Symfony\\\\Component\\\\HttpKernel\\\\Event\\\\GetResponseEvent: {})\",\"kernel.request\",\"[object] (Symfony\\\\Component\\\\EventDispatcher\\\\ContainerAwareEventDispatcher: {})\"]}",
"/.../vendor/symfony/symfony/src/Symfony/Component/EventDispatcher/EventDispatcher.php:184",
"/.../vendor/symfony/symfony/src/Symfony/Component/EventDispatcher/EventDispatcher.php:46",
]
}
}
Extra:
request_ip:
46.235.158.196
client_ip:
46.235.158.196
session:
[]
get:
[]
post:
[]
server:
{
"content-type": [
""
],
"content-length": [
""
],
"accept": [
"*/*"
],
"accept-language": [
"en, *;q=0.7"
],
"user-agent": [
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; Trident/7.0; rv:11.0) like Gecko"
],
"host": [
"test.com"
],
"connection": [
"Keep-Alive"
],
"x-php-ob-level": [
1
]
}
attr:
[]
cookies:
[]
files:
[]

Related

laravel: routing error when sending validation error messages

I do not understand what is wrong with this code being at the address 127.0.0.1:8000/getIncomingTransfers I am trying to process a form by sending it to the address 127.0.0.1:8000/authenticateTransfer but I get the error The GET method is not supported for this route. Supported methods: POST.
in my web.php file
Route::name('reference')->post('getIncomingTransfers', [MainController::class, 'getIncomingTransfers']);
Route::name('security')->post('authenticateTransfer', [MainController::class, 'authenticateTransfer']);
in my getIncomingTransfers.blade.php file
<form action="{{ route('security') }}" method="post">
#csrf
<div class="form-group">
<input type="text" class="form-control {{ $errors->has('SecurityAnswer') ? 'error' : '' }}" name="SecurityAnswer" id="SecurityAnswer">
<button type="submit" name="send" class="btn btn-primary solid">Confirm</button>
</div>
<!-- Error -->
#if ($errors->has('SecurityAnswer'))
<div class="error" style="text-align: center; color: brown">
{{ $errors->first('SecurityAnswer') }}
</div>
#endif
</form>
in my MainController#authenticateTransfer file
public function authenticateTransfer(Request $request)
{
$this->validate($request, [
'SecurityAnswer' => 'required',
]);
return $request;
}
when I click on the submit button of the form with the SecurityAnswer field not empty there is no error but when the validation fails and the message of the validation error must be returned that's where I have this error. how can i solve the problem?.
I also want to specify that the getIncomingTransfers route is in POST by which a form is received to be processed before returning the view getIncomingTransfers.blade.php

No field in my form exists when validation fails

I have a strange problem on symfony 6.1
I searched, but I couldn't find the solution.
The error message: Neither the property "_token" nor one of the methods "_token()", "get_token()"/"is_token()"/"has_token()" or "__call()" exist and have public access in class "Symfony\Component\Form\FormView".
The error occurs when validation fails Error screen
#[Route('/new', name: 'app_commande_new', methods: ['GET', 'POST'])]
public function new(Request $request, ProductRepository $productRepository): Response
{
$commande = new Commande();
$form = $this->createForm(CommandeType::class, $commande);
//dd($request);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
dd($form->getData());
return $this->redirectToRoute('app_commande_index', [], Response::HTTP_SEE_OTHER);
}
//dd($form);
return $this->renderForm('commande/new.html.twig', [
'commande' => $commande,
'form' => $form,
]);
}
View
{{ form_start(form) }}
<div class="row">
<div class="col-md-6">
{{ form_row(form._token) }}
{{ form_row(form.client) }}
</div>
<div class="col-md-6">
{{ form_row(form.limitDate) }}
</div>
</div>
<button class="btn btn-primary" id="save" type="submit">{{ button_label|default('Save') }}</button>
{{ form_end(form, {render_rest: false}) }}
My post can't take more code here are the pictures of the forms code.
CommandeType
ProductOutType

Unsure why my endpoint URL is throwing a 404 error upon making a post request

I've been facing this issue for a few days - I'm not sure why I'm getting a 404 error even though my endpoint URL is correct. I know it's correct because I've even verified through via the Network tab. I'm testing via Postman and the API's working fine but some reason, the endpoint just can't be found.
My guess is that I probably need to include some additional code in my api.php file to make sure the URL can be properly read when making post request? Or maybe it's something in my RegisterController But I'm not entirely sure.
Upon submitting the form I get a 405 error that says: The POST method is not supported for this route. Supported methods: GET, HEAD. which makes no sense because it's clearly a post request.
I've tried too many ways to list here in an attempt to rectify this but to no avail. Does anyone have any suggestions on what I can try to do to fix this?
Here's my react.js file
import React, { useState} from 'react';
import '../../../sass/LoginSignUp/LoginSignUp.scss'
import axios from 'axios';
const LoginSignUp = () => {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const handleSubmit = () => {
let data = {
'name': name,
'email': email,
'password': password,
'confirmPassword': confirmPassword
}
let headers = {
Accept: 'application/json'
}
axios.post('http://website.test/api/register', data, {headers})
.then(data => {
console.log(data);
}).catch(error => {
console.log(error);
});
}
return (
<div className="section">
<div className="container">
<div className="row full-height justify-content-center">
<div className="col-12 text-center align-self-center py-5">
<div className="section pb-5 pt-5 pt-sm-2 text-center">
<h6 className="mb-0 pb-3"><span>Log In </span><span>Sign Up</span></h6>
<input className="checkbox" type="checkbox" id="reg-log" name="reg-log"/>
<label htmlFor="reg-log"></label>
<div className="card-3d-wrap mx-auto">
<div className="card-3d-wrapper">
<form method="POST" onSubmit={handleSubmit}>
<div className="card-back">
<div className="center-wrap">
<div className="section text-center">
<h4 className="mb-4 pb-3">Sign Up</h4>
<div className="form-group">
<input type="text" name="logname"
className="form-style"
placeholder="Username"
id="userName"
autoComplete="none"
onChange={(e) => setName(e.target.value)}
/>
<i className="input-icon uil uil-user"></i>
</div>
<div className="form-group mt-2">
<input type="email" name="logemail"
className="form-style"
placeholder="Your Email"
id="logemail"
autoComplete="none"
onChange={(e) => setEmail(e.target.value)}
/>
<i className="input-icon uil uil-at"></i>
</div>
<div className="form-group mt-2">
<input type="password" name="logpass"
className="form-style"
placeholder="Your Password"
id="logpass"
autoComplete="none"
onChange={(e) => setPassword(e.target.value)}
/>
<i className="input-icon uil uil-lock-alt"></i>
</div>
<div className="form-group mt-2">
<input type="password" name="logpass"
className="form-style"
placeholder="Confirm Password"
id="logpass"
autoComplete="none"
onChange={(e) => setConfirmPassword(e.target.value)}
/>
<i className="input-icon uil uil-lock-alt"></i>
</div>
<button className="btn mt-4">Submit</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
export default LoginSignUp;
Here's my RegisterController:
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
'c_password' => 'required|same:password',
]);
if ($validator->fails()) {
return $this->sendError('Validation Error.', $validator->errors());
}
$userId = 'u-' . Str::uuid()->toString();
$input = $request->all();
$input['password'] = bcrypt($input['password']);
$input['UserID'] = $userId;
$user = User::create($input);
$input['name'] = $user->name;
$success['token'] = $user->createToken('MyApp')->accessToken;
return $this->sendResponse($success, 'User registered successfully.');
}
Here's complete api.php:
<?php
use App\Http\Controllers\API\RegisterController;
use App\Http\Controllers\API\PhotosController;
use Illuminate\Support\Facades\Route;
Route::post('register', [RegisterController::class, 'register']);
Route::post('login', [RegisterController::class, 'login']);
Route::middleware('auth:api')->group( function () {
Route::resource('photos', PhotosController::class);
});
I think you need to handle cors request
You can install this package
https://github.com/fruitcake/laravel-cors
To generate config file run following command
php artisan vendor:publish --tag="cors"
and then update
in config/cors.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Cross-Origin Resource Sharing (CORS) Configuration
|--------------------------------------------------------------------------
|
| Here you may configure your settings for cross-origin resource sharing
| or "CORS". This determines what cross-origin operations may execute
| in web browsers. You are free to adjust these settings as needed.
|
| To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
|
*/
'paths' => ['api/*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
];
To allow CORS for all your routes, add the HandleCors middleware at the top of the $middleware property of app/Http/Kernel.php class:
protected $middleware = [
\Fruitcake\Cors\HandleCors::class,
// ...
];

Pulling data back to the blade without refreshing

So I'm pretty new to laravel in general, and what I have is a search form that pulls information from the database and then calls it back on the same page, currently it's working like a redirect but I would like to know how to do this without having to refresh the page
This is the blade:
<form class="form-horizontal" role="form" id="policy-documents-search-form" action="/search" method="POST">
{{ csrf_field() }}
<fieldset>
<div class="form-group">
<label for="username" class="col-sm-6 control-label">Enter your policy number</label>
<div class="col-sm-8">
<input type="text" name="ordernumber" id="ordernumber" class="form-control"/>
<span class="text-danger">{{ $errors->first('ordernumber') }}</span>
</div>
</div>
#if (session('error'))
<div class="alert alert-danger">{{ session('error') }}</div>
#endif
<div class="form-group">
<div class="col-sm-offset-4 col-sm-8">
<button type="submit" class="btn btn-primary" id="search-button">Search</button>
</div>
</div>
<div class="form-group">
<div class="container">
#if(isset($order))
<h2>Your Policy Details</h2>
<table>
<thead>
<tr>
<th>Name</th>
<th>Claims Telephone</th>
<th>Policy Wording</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{ #$order->scheme->Description }}</td>
<td>{{ #$order->scheme->ClaimsTelephone1 }}</td>
<td>Policy Wording </td>
</tr>
</tbody>
</table>
#endif
</div>
</div>
</div>
</fieldset>
</form>
This is the Controller function:
public function search(Request $request) {
if ($this->validate($request, [
'ordernumber' => 'string|min:8|max:16',
], [
'ordernumber.string' => ' Please enter a full order number. This will either be 8, 12 or 16 characters long and include a 2 letter prefix.',
'ordernumber.min' => ' Please enter a full order number. This will either be 8, 12 or 16 characters long and include a 2 letter prefix.',
'ordernumber.max' => ' Please enter a full order number. This will either be 8, 12 or 16 characters long and include a 2 letter prefix.',
]));
try {
$order = Order::findOrFail(decodeFullOrderNumber($request->ordernumber));
} catch (ModelNotFoundException $exception) {
return back()->withError('We could not find this policy number in our system, please try again')->withInput();
}
return view('policy_wording', compact('order'), [
'title' => "Policy Wording Results",
]);
}
And this is the route:
Route::get('/policy-wording',
'PolicyWordingController#policyWordingPage');
Route::any('/search', 'PolicyWordingController#search');
First of all i suggest to use Vuejs for that purposes so u can not think about how to rebuild your table, etc.
On the serverside all you need to do is return search result if was ajax
if ($request->isXmlHttpRequest())
return $order->toArray();
before return view()
To do it with AJAX, you need a front end solution, like Axios or jQuery, in order to make the AJAX requests.
Once the request is sent, you can handle it like a regular POST request and then return a JSON or a html.
For JSON, it's pretty simple, every array or model you return will be converted to JSON by default.
To return a view however, you need to use the render method. This method will "render" the view and return you the corresponding HTML.
So, instead of :
return view('policy_wording', compact('order'), [
'title' => "Policy Wording Results",
]);
you should have something like :
return view('policy_wording', compact('order'), [
'title' => "Policy Wording Results",
])->render(); //notice the render method here
Then all you need to do is to handle the response in your front-end.
Edit about validation
If your validation fails, it'll return a 422 error (Unprocessable Entity), so you can handle it like any other ajax error.

Laravel simple validation doens't work on resource method

Basically i have this form on userblog/create.blade.php
<form action="{{route('userblog.store')}}" method="POST">
{{csrf_field()}}
<div class="form-group">
<div class="row">
<div class="col-md-12">
<label style="font-family: SansBold">تیتر وبلاگ:</label>
<input type="text" name="blog_title"
class="form-control">
</div>
</div>
</div>
<div class="text-right">
<button type="submit" class="btn btn-primary">
Save
<i class="icon-arrow-left13 position-right"></i></button>
</div>
<br/>
</form>
with this route on web.php
Route::group(['middleware' => ['auth:web'], 'prefix' => 'page'], function () {
$this->resource('userBlog', 'UserBlogController');
});
now I'm trying to check posted form on Controller with this code and store them on database:
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'blog_title' => 'required|min:10',
'blog_content' => 'required|min:10',
]);
if ($validator->failed()) {
return back();
} else {
dd('store on database');
}
}
in this my code i get
Route [userblog.store] not defined
error and when i change form action to /page/userBlog i get [] on $validator
The routes name should be like resource name. Replace your resource name or Route name like:
$this->resource('userblog', 'UserBlogController');
or
.. action="{{route('userBlog.store')}}"
BTW, It's not a validation error. Just fix your route.

Categories