Undefined offset: 0 when using ->with_input() - laravel - laravel

I'm getting this error when using with_input() to keep the user old input data after submiting with validation errors:
ErrorException
Undefined offset: 0
the code for redirect is:
return Redirect::to('login')->with_input();

I am not sure which version of Laravel you are using, but your code should be:
return Redirect::to('login')->withInput();
and if you are returning errors too, you might consider using withErrors() in addition:
Route::post('register', function()
{
$rules = array(...);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
return Redirect::to('register')->withErrors($validator);
}
});
Check the docs:
http://laravel.com/docs/validation#error-messages-and-views

If you're using Laravel 4, you need to use withInput instead of with_input

Related

Laravel validation couldn't store value after validate and give error 500

I have a form that using ajax for update data client. In that form there is an input file. Everything is going fine except for updating the file. File is sent, it changed on storage too, but it gives error on validation and didn't change data on database.
Here is the code on the controller :
public function update(Request $request, Client $client)
{
$validatedData = Validator::make($request->all(), [
'name' => 'required|max:255',
'logo'=> 'image|file|max:100',
'level' => 'required|max:1'
]);
$validatedData['user_id'] = auth()->user()->id;
if ($validatedData->fails()){
return response()->json($validatedData->errors());
} else {
if($request->file('logo')){
if($request->oldLogo){
Storage::delete($request->oldLogo);
}
$validatedData['logo'] = $request->file('logo')->store('logo-clients');
}
$validateFix = $validatedData->validate();
Client::where('id', $client->id)->update($validateFix);
return response()->json([
'success' => 'Success!'
]);
}
}
It gives error on line :
$validatedData['logo'] = $request->file('logo')->store('logo-clients');
With message :
"Cannot use object of type Illuminate\Validation\Validator as array"
I use the same code that works on another case, the difference is the other not using ajax or I didn't use Validator::make on file input. I guess it's just wrong syntax but I don't really know where and what it is.
To retrieve the validated input of a Validator, use the validated() function like so:
$validated = $validator->validated();
Docs:
https://laravel.com/docs/9.x/validation#manually-creating-validators
https://laravel.com/api/9.x/Illuminate/Contracts/Validation/Validator.html
$validatedData is an object of type Illuminate\Validation\Validator.
I would say the error is earlier there as well as this line should give an error also:
$validatedData['user_id'] = auth()->user()->id;
As ericmp said, you first need to retrieve the validateddata to an array and then work with it.

Laravel form request messages not appearing when validation fails

my store method
the FormRequest
the validation is working and I get the confirm message in controller but when the validation fails I get no error messages any advice?
You can use validation in controller like this, hopefully it will work for you
$validator = Validator::make($request->all(), [
'id' => 'required|string|regex:/(^([A-Z]){2,4}_([0-1]){1}_([0-1]){1}_([0-9]){10})/u'
]);
if ($validator->fails()){
return (Arr::first(Arr::flatten($validator->messages()->get('*')));
}
else{
//your code
}
protected function failedValidation(Validator $validator)
{
throw new HttpResponseException(response()->json([
'errors' => $validator->errors(),], 403));
}
this worked for me, just needed to return the errors in json format

Laravel Jetstream Route Test With Inertia Returns Error Code 500

Out the test it works, I can visit the page and the controller wroks fine. I wrote the following test:
public function test_logged_user_is_not_redirected()
{
PartnerFactory::new()->create();
$request = $this->actingAs(UserFactory::new()->create())
->get('partners')
->assertRedirect('partners');
dd($request->inertiaProps());
}
I get error code 500. This is the controller:
public function index()
{
return Inertia::render('Partners/Index', [
'filters' => \Illuminate\Support\Facades\Request::all($this->getFilters()),
'contacts' => function() {
return $this->getAllContacts();
}
]);
}
This is the route in web.php
Route::get('partners', [PartnersController::class, 'index'])
->name('partners')
->middleware('auth');
Using refresh database, tried url with a '/' before, I still get 500.
edit: without exception handling i get: Trying to get property 'id' of non-object
Found the solution: The user in jetstream MUST have the personal team!

Error using withErrors() when returning view

I would like to submit my laravel form, with some errors if my csv is not set to the input file.
So I did like this, simple, basic :
public function store(Request $request) {
$validator = Validator::make($request->all(), [
'csv' => 'required|mimes:csv',
]);
if($validator->fails())
{
return view(backpack_view('upload/upload-nb-postes'))->withErrors($validator);
}
}
The validator fails, of course, so it should render my view with error messages but I have an error :
Facade\Ignition\Exceptions\ViewException
Call to undefined method Illuminate\Support\MessageBag::getBag()
I checked the MessageBag class and ... yes, there is no getBag() method.
So what should I do ? I can't use the withErrors() method...
I tried with :
return view(backpack_view('upload/upload-nb-postes'))->withErrors(['csv' = > 'test');
Same problem, I also checked that there is some error messages.
Maybe update with composer ? I won't crash my project.
More information :
Laravel version : 6.17.1
Laravel locale : fr
Laravel config cached : false
PHP version : 7.4.3
You have to call errors method of $validator instance.
return view(backpack_view('upload/upload-nb-postes'))->withErrors($validator->errors());
Inside your view, use $errors->first('csv') to access error message.

Laravel if one of the fields is not set, laravel throws error

I have very big problem.
When I submit my form with data everything goes well, but when I won't fill one field in my form laravel throw error MethodNotAllowedHttpException in RouteCollection.php line 218
I have validation in my controller but it does not change anything. When the form is empty it throws an error.
Somebody has a solution for this error?
In your route for this form post use veriables as optional. Use ? In your route definition.
/{var?}/{var2?}/......
From laravel docs-
Occasionally you may need to specify a route parameter, but make the presence of that route parameter optional. You may do so by placing a ? mark after the parameter name. Make sure to give the route's corresponding variable a default value:
Route::get('user/{name?}', function ($name = null) {
return $name;
});
Route::get('user/{name?}', function ($name = 'John') {
return $name;
});
or
// validate the info, create rules for the inputs
$rules = array('data_rozpoczecia' => 'required', 'data_zakonczenia' => 'required');
// run the validation rules on the inputs from the form
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) { return redirect()->back(); } else{ //do what you want. }

Resources