I'm pretty new to Laravel. I'm trying to create a form to post to a function in my controller. It works fine, exactly as expected, until I try to add in a custom request validation. As soon as I've added it, if I run the form again I get a MethodNotAllowed error. Can someone tell me what is going wrong?
edit** sorry I forgot to post the code.
The request I made is pretty simple. The authorize is set to return true.
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'campaign_name'=>'required',
'campaign_message'=>'required_without:campaign_link',
];
}
In the controller I'm calling the namespace for the request at the top and have the function using that request. The function works just fine when the regular laravel request is called rather than my custom one.
public function store(CreateCampaignRequest $request)
{
//do code here
}
My form is using this action to send the request.
{!! Form::open(['method'=>'POST',
'action'=>'OrganizationCampaignController#store'])!!}
and the route is set to this
Route::post('dashboard/campaigns/send','OrganizationCampaignController#store');
Like I said everything works when the normal Request is called, it only throws the method not allowed when I try using my custom request.
Thank you!
Related
I'm working on a Laravel 5.4 project and have multiple pages with the same url e.g. www.blahblah.com/order/verify/{encryption_key}
My routs are:
Route::get('/order/verify/{encrypted_key}','PinVerificationController#init');
Route::post('/order/verify/{encrypted_key}','PinVerificationController#pinValidation');
The flow is they land on a page first where they enter their phone number, then they go to a second page where they have to enter a pin code. I validate if the pin code is a number, if it isn't then I redirect back with an error message. But they're being redirected to the first page instead.
If the validation fails i'm routing back. I'm doing
return \Redirect::back()->withInput()->withErrors($validator);
but this is routing to the GET page instead of the POST page.
Why is this happening?
UPDATE #1
public function init(){
$country_extensions = appUtils::getCountryExtensionDropdown();
//TODO
$country_iso_code = "1-US";
$parameters = compact( 'country_extensions','country_iso_code' );
return view('/pages/choose_phone_verify_method',$parameters);
}
private function pinValidation(Request $request){
$validator = \Validator::make($request->all(), [
'pin_number' => 'required|numeric'
]);
if ($validator->fails()) {
return \Redirect::back()->withInput()->withErrors($validator);
}
}
I don't know if you make your validation in a controller or in a request. But as I can see you redirect back(), and it must be from your controller.
My suggestion is you use the formRequest class instead of the validator in your controller.
You see, the getRedirectUrl() method of the FormRequest class, tests for some special properties on the class, and if it doesn't find any value, it falls back to a redirect, using the Illuminate\Routing\UrlGenerator::previous() generated URL. Those properties that the FormRequest checks, are the redirection options you have.
Now you have two options of changing them, either globally in every form request you make, by putting the property in the abstract class App\Http\Requests\Request that every form request class inherits from. Or, in particular, form classes, by simply putting them in the form class itself.
And these are all the options you have for custom redirections :
protected $redirect; // A simple URL. ex: google.com
protected $redirectRoute; // A route name to redirect to.
protected $redirectAction; // A controller action to redirect to.
But if you insist do the validation in your controller you can write an if statement. so that if the validator fails it redirect to a specific path like page 2 path in this situation. like this code below:
if ($validator->fails()) {
return redirect('path to page 2')->withInput()->withErrors($validator);
}
Or you can redirect to route name:
if ($validator->fails()) {
return redirect(route('route name'))->withInput()->withErrors($validator);
}
Wouldn't it be easier to just handle the post request in the same method (init()).
That way you would need to redirect, but just display the errors.
And the user could easily correct his errors (since the form could be filled out, and it's automatically shown again) and submit the form again.
I have Laravel app with Vue on front end, and Vue calls update method from controller using PUT request.
Request works, model gets updated, but I have issue with redirecting as it is redirecting also as a PUT instead of simple GET?
public function update(MomentsValidationRequest $request, Project $project, Task $task, Moment $moment)
{
foreach($request->materials as $material){
$material_id_array[$material['id']] = ['quantity' => $material['quantity']];
}
$moment->update($request->all());
if(isset($material_id_array))
$moment->materials()->sync($material_id_array);
return redirect()->back()->with(['alert-type' => 'success', 'message' => 'Moment updated!']);
}
So naturally, I am getting a method not allowed exception because it is redirecting to a route which is supposed to get a previous view only.
Route itself is fine, request method isn't.
For non-believers :)
Also a route:
I know this is a bit late. But incase anyone stumbles across this.
You state that you're using Vue in the front end. This would suggest that the put request is being made through an axios call.
I can't see this call, so this is only an assumption. But I believe the solution would be to return a json object instead of a response in the controller, and then redirect trigger a redirect from the Vue component itself.
In the controller:
Session::flash('alert-type', 'success');
Session::flash('message', 'Moment updated!');
return response()->json(true);
In the component:
axios.post('/moments', this.moment).then(() => {
window.location.replace("moments");
});
I believe this is something to do with how axios handles patch requests, it seems to attempt to handle a redirect response automatically, I could be wrong though, so any reply is welcome to if there's a better explanation.
You can use:
redirect()->back(303)->with(...)
No, redirection is made always with GET but you don't have such route defined. So you should create GET route that will do something with this.
It's possible only to redirect to GET routes.
As mention in https://github.com/laravel/framework/issues/10791
If we want to get the Merge request from middleware in the Form request
We could add the below function in our Form request
public function all()
{
$this->merge( $this->request->all() );
return parent::all();
}
But when i tried to use that function in my CartRequest i get an error
(2/2) ReflectionException
Class App\Http\Requests\Product\CartRequest does not exist
in RouteSignatureParameters.php (line 25)
I dont know why i could not use that method
NB : im using laravel 5.5
Rigth now, i call 2 request in my controller to get my custom request
function addCart(Request $request,CartRequest $cartRequest,$item_id){
$global_id = $request->globalId //this id is coming from middleware
}
But i think that is the bad method.
Is there any other method to get our custom request in middleware?
I'm developing a RESTful API with Laravel 5.3, so I'm testing some functions and request with my controllers. One thing I need to do is validate the request that my user sends before add a field in my database, so, I use a custom FormRequest to validate it.
When I tested my API in Postman and send my invalid request, response redirect me to homepage. After reading documentation, I found the following statement
If validation fails, a redirect response will be generated to send the
user back to their previous location. The errors will also be flashed
to the session so they are available for display. If the request was
an AJAX request, a HTTP response with a 422 status code will be
returned to the user including a JSON representation of the validation
errors.
How can I prevent this? Or there is a AJAX mode in Postman? Any suggestion?
Also this can be achieved without overriding any function. Laravel is built to support both Json & normal pages.
Please change your settings in postman and set Accept to application/json like below
Laravel is SMART ;-)
Your custom FormRequest extends Illuminate\Foundation\Http\FormRequest. Within is a function that performs the redirect called response(). Simply override this function within your custom FormRequest to change how invalid validations are responded to.
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\JsonResponse;
class CustomFormRequest extends FormRequest
{
/**
* Custom Failed Response
*
* Overrides the Illuminate\Foundation\Http\FormRequest
* response function to stop it from auto redirecting
* and applies a API custom response format.
*
* #param array $errors
* #return JsonResponse
*/
public function response(array $errors) {
// Put whatever response you want here.
return new JsonResponse([
'status' => '422',
'errors' => $errors,
], 422);
}
}
I faced same problem in Laravel 8. In your request class, you can override failedValidation method.
<?php
...
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
class RegisterRequest extends FormRequest
{
...
protected function failedValidation(Validator $validator)
{
throw new HttpResponseException(response()->json(['errors' => $validator->errors()], 422));
}
...
}
just started doing some symfony. The root URL i.e. /, works fine and the index/home page is returned well with all the contents. However, I just added a new route i.e. /contact, with it's required controller. When I try to get theis new contact page on a browser, I just get an empty page yet it returns a 200 response code, meaning the request was successful. Quite confusing for me. What could be the problem? Not much code for now since I got no logic but here's my controller:
class ContactController extends Controller
{
/**
* #Route("/contact")
* #Template()
*/
public function contactAction()
{
return array(
// ...
); }
}
If you load the page from app_dev.php, for example http://yourdomain.net/app_dev.php/contact, in log you can check which controller is called, and then you can debug from there the response.