I'm trying to validate post request. I think when the validation fails, it gives me this error message.
app/Http/Controllers/InternationalShippingController.php
public function store(Request $request){
//echo '<pre>';
$post = $request->post();
$order_ids = session('international_order_ids');
//var_dump($order_ids);
//var_dump($post);
$validator = Validator::make(
$post,[
'documents.*' => 'mimes:jpg,jpeg,png,pdf|max:5000|nullable',
'company_name' => 'nullable',
'shipping_address1' => 'nullable',
'message' => 'size:1000',
],[
'image_file.*.mimes' => __('Only jpeg,png and pdf files are allowed'),
'image_file.*.max' => __('Sorry! Maximum allowed size for an document is 5MB'),
]
);
if($validator->fails()){
return redirect('internationalshippings/create2')
->withErrors($validator)
->withInput();
}
}
web.php
Route::post('internationalshippings/create2','InternationalShippingController#create2');
Route::resource('internationalshippings','InternationalShippingController');
I haven't made show() method in the controller.
Does this error mean when the validation fails, it tries to redirect to internationalshippings/show method?
When the validation fails,I'd like this to redirect back to internationalshippings/create2. How can I achieve this?
Thank you
you are using the resource controller,
in resources this url internationalshippings/SomeThing means the show method i mean this url calls the show method in resource
First way
so you can use this in your fail return:
return redirect()->route('your_route_name') OR return back()
Second way
and the second way is in your web.php, when you are defining the resource route, type in this way:
Route::resource('internationalshippings','InternationalShippingController',['except'=>['show']]);
EDIT:
in your code situation the best way is change Return, because the url that you want to redirect to it, is POST
Related
I wanted to validate inputs from a GET request without using the
this->validate($request... or \Validator::make($request...
and prefer to do it like
$input = $request->validate([... rules ...]);
however since get requests doesn't have $request parameters how can I achieve it?
public function sampleGet($param1, $param2) {
// How can I pass the $param1 and $param to to validate?
$input = $request->validate([
'param1' => 'required',
'param2' => 'required
]);
}
You can do so and it will have same behavior as validate
validator($request->route()->parameters(), [
'param1' => 'required',
'param2' => 'required'
....
])->validate();
If you want all the route parameters you can get them as an array:
$request->route()->parameters()
Since you already have those parameters being passed to your method you can just build an array with them:
compact('param1', 'param2');
// or
['param1' => $param1, 'param2' => $param2];
You are not going to be using the validate method on the Request though, you will have to manually create a validator. Unless you want to merge this array into the request or create a new request with these as inputs.
There is nothing special about the validate method on a Controller or on a Request. They are all making a validator and validating the data the same way you would yourself.
When manually creating a validator you still have a validate method that will throw an exception, which would be the equivalent to what is happening on Request and the Controller with their validate methods.
Laravel 7.x Docs - Validation - Manualy Creating Validators - Automatic Redirection
You can do like that.
public function getData(Request $request)
{
try {
$input['route1'] = $request->route('route1');
$input['route2'] = $request->route('route2');
$valid = Validator::make($input, [
'route1' => 'required',
'route2' => 'required'
]);
} catch (\Throwable $th) {
echo "<pre>";print_r($th->__toString());die;
}
}
Or you can follow the below link for more info.
https://laravel.com/docs/7.x/validation#manually-creating-validators
im trying in my controller method to pass some data to a order sucess page, information regarding the details of payment, but i cant make it work or pass the data.
In my case i wish for example pass this request
$http = new \GuzzleHttp\Client;
$response = $http->request('POST', 'https://domain', [
'form_params' => [
'chave' => 'somekey',
'valor' => Cart::total(),
'id' => $order->id,
]
]);
$result = json_decode((string) $response->getBody(),true);
Cart::destroy();
return redirect()->route('frontend-cart-success')->with( ['data' => $result] );
And then in my view sucess page just calling the $data Info to show on my blade file.
But i cant it ut it work.
My route to pass in sucess page:
Route::get('cart/success/', 'Frontend\CartController#showSuccess')->name('frontend-cart-success');
Best regards
I code mostly in SPAs, but according to the API (https://github.com/laravel/framework/blob/5.7/src/Illuminate/Http/RedirectResponse.php#L42), it's flashing that data to the session, so you're going to have to get the data back out using the session.
See: https://laracasts.com/discuss/channels/laravel/redirect-to-route-with-data?page=1
I' working with Laravel 5.6 and i've decided to create a resource controller to handle one of my models. Right know im trying to destroy a record from the database like this:
public function destroy(Role $role)
{
$role->delete();
return response([
'alert' => [
'type' => 'success',
'title' => 'Role destroyed!'
]
], 200);
}
It works just fine as longs as the $role exists. My problem is that i want to handle the response myself in the case that $role does not exist to do something like this:
return response([
'alert' => [
'type' => 'ups!',
'title' => 'There is no role with the provided id!'
]
], 400);
But instead, i'm getting a error like this:
"No query results for model [App\\Models\\Role]."
And that is something I don't want.
Thanks in advance!
The "No query results for model [App\\Models\\Role]." is the standard response message for a ModelNotFound exception in Laravel.
The best way to change the response for an exception like this is to use the exception handler's render function to respond with whatever message you want.
For example you could do
if ($e instanceof ModelNotFoundException) {
$response['type'] = "ups!;
$response['message'] = "Could not find what you're looking for";
$response['status'] = Response::HTTP_NOT_FOUND
}
return response()->json(['alert' => $response], $response['status']);
The alternative is to ensure that the ModelNotFound exception does not get thrown (So use ->find() rather than ->findOrFail() when querying the model)
and then using the abort helper like so if no results are returned:
abort(400, 'Role not found');
or
return response(['alert' => [
'type' => 'ups!',
'title' => 'There is no role with the provided id!']
],400);
I validate POST request like:
$validator = Validator::make($request->all(), [
"id.*" => 'required|integer'
]);
if ($validator->fails()) {
return response()->json($validator->errors, 400);
}
echo "Ok";
When I send request without parameter id it skips validation and returns echo "Ok";.
Why validation does not work?
If you expect id is array of integers you should update validation rules like this:
$validator = Validator::make($request->all(), [
"id" => 'required|array',
"id.*" => 'integer'
]);
First know when using $request->validate(); when it fail exceptions are raised!
And they are automatically handled by laravel. If it's a get, or a normal post form, then the process will redirect back to the form.
To note, when using the validate method during an AJAX request, Laravel will not generate a redirect response. Instead, Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code.
If you want to not have such an automatic behavior, create manually a validator, then you can check with ->fails() method, as the example show bellow. That's can be handful in a lot of situations.
<?php
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}
// Store the blog post...
}
}
And there is no better then the doc itself: https://laravel.com/docs/5.7/validation
there is a lot of options, to personalize our validation process.
Type error: Argument 1 passed to App\Http\Controllers\Controller::validate() must be an instance of Illuminate\Http\Request, array given, called in app\Http\Controllers\RegistrationController.php on line 23
It doesn't work here
Registration Controller
but at the same time works fine in another controller
AuthController
The reason you're getting this error is because you're passing your validation rules to the request() helper function and not as the 2nd param to $this->validate()
You can still use the request() helper function but you just need to do:
$this->validate(request(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'password|confirmed', //<-- Is the password rule something you've created?!?
]);
Hope this helps!
function store()should be function store(Request $request) if you want to use the request. However #CBroe is right: please learn to ask your questions better.