Default value for laravel collective select - laravel

I have a Laravel collective select as follows:
{!! Form::select('phone', $numbers, $title, ['class' => 'phone-select2 col4', 'id' => 'phone']) !!}
I want to pass default value for dropdown as separate variable from $numbers. So, have passed it as $title but it is didn't work due to it is not in the $numbers. So, how can I pass default value for it?

What you're looking for is a placeholder.
https://laravelcollective.com/docs/6.x/html#drop-down-lists
According to the documentation, you can set the default value to null and provide placeholder attribute as part of the fourth argument:
['class' => 'phone-select2 col4', 'id' => 'phone', 'placeholder' => 'Pick an option']

Related

Laravel required_with throwing error even when its supposed to be ignored

Basic user profile update page with an optional password change. Only if theyre trying to change their password, does it request the current password.
Controller:
$this->validate($request, [
'name' => 'required',
'email' => 'required|email',
'new_password' => 'confirmed',
'current_password' => 'required_with:new_password|current_password'
]);
$user->name = $request->get('name');
$user->surname = $request->get('surname');
$user->email = $request->get('email');
if($request->get('password') !== ''){
$user->password = Hash::make($request->get('new_password'));
}
$user->save();
But validation keeps tripping up and giving me the error "validation.current_password"
View (scaled back for readability):
#if($errors)
#foreach ($errors->all() as $error)
<div>{{ $error }}</div>
#endforeach
#endif
{!! Form::model($user, ['method'=>'PATCH', 'action'=>['UserController#update', $user->id], 'class'=>'kt-form kt-form--state', 'id'=>'form-user-profile', 'files' => true]) !!}
{!! Form::text('name', null, ['class'=>'form-control']) !!}
{!! Form::password('current_password', ['class'=>'form-control','placeholder'=>__('Current Password')]) !!}
{!! Form::password('new_password', ['class'=>'form-control','placeholder'=>__('New Password')]) !!}
{!! Form::password('new_password_confirmation', ['class'=>'form-control','placeholder'=>__('Verify New Password')]) !!}
{{ Form::button(__('Submit'), ['type' => 'submit', 'class' => 'btn btn-success']) }}
{{ Form::button(__('Reset'), ['type' => 'reset', 'class' => 'btn btn-secondary']) }}
{!! Form::close() !!}
As per https://laravel.com/docs/9.x/validation#rule-required-with
required_with only needs to be present if new_password is present. So why am I getting a "validation.current_password" error when I only update my "name" field (for example).
From the error you're getting, it is somehow clear that the required_with is not the rule behind the error, it actually is the current_password rule.
According to the docs, the current_password rule does the following check
The field under validation must match the authenticated user's password
So with that being said, it seems you're not typing the correct password of the currently logged in user which trigger the validation error of the current_password rule.
A quick fix could be:
starting by adding the nullable validation rule on both new_password and current_password fields so the validation can pass when the fields are empty.
use required_unless rule instead of required_with which allows you to verify whether new_password field is empty (null) or not.
required_unless: The field under validation must be present and not empty unless the anotherfield field is equal to any value. This also means anotherfield must be present in the request data unless value is null. If value is null (required_unless:name,null), the field under validation will be required unless the comparison field is null or the comparison field is missing from the request data.
Here's a code sample illustrating what's being said:
$this->validate($request, [
'name' => 'required',
'email' => ['required', 'email'],
'new_password' => ['nullable', 'confirmed'],
'current_password' => ['nullable', 'required_unless:new_password,null', 'current_password']
]);
In the above code sample i used arrays instead of strings to specify the rules. This doesn't have anything to do with the solution, it is used to make the changes clearer and the code more readable
Bonus Tip: you're getting validation.current_password as the error message is due to the lang files that contain the validation message being deleted. TheEN version of those files should be under resources/lang/en/validation.php. You may simply download that file from GitHub and place it there or you may use your own custom error messages.
Learn more about Validation Rules on Laravel docs.

Wrong type being displayed

I am just trying to figure out why this is happening. I have a form with the following input
{!! Form::input('number', 'numTemplates', '1', ['id' => 'numTemplates', 'class' => 'form-control', 'min' => '1']) !!}
Now I presume number would be treated as an integer? Within my Controller I am doing the following
$templates = $request->input('numTemplates');
dd(gettype($templates));
The output of this is "string". So why would a number input be displayed as a string when using gettype?
Thanks
It's a string because it's still a value of HTML form input. Just do type conversion, something like intval($request->numTemplates) or (int)$request->numTemplates

Laravel/Eloquent: Issues with date mutation and form model binding

I have a column with datatype of date which is date mutated. I date mutated it so that Laravel will convert it to a Carbon instance and I can use it easily at other places, where I need to convert it into Carbon instance. I am using Model binding in the edit form. As the field is date mutated, on the edit form it appears as "2015-07-29 00:00:00". I need it to be in this format instead: "2015-07-29".
I can't use accessor, as I need it as a Carbon instance at many other places.
I can't explicitly pass value after converting, as I am using the input inside a form partial and I also use it for create.
My workaround is the following:
I am sending a flag while including the view partial in the edit page and using it a condition to have two different code for create and edit.
#if (isset($edit))
{!! Form::text('eta', $order->eta->format('Y-m-d'), ['class' => 'form-control', 'required']) !!}
#else
{!! Form::text('eta', null, ['class' => 'form-control', 'required']) !!}
#endif
Is there a better way?
I think you can avoid from #if and $edit as,
{!! Form::text('eta', ( $order->eta ? $order->eta->format('Y-m-d') : null ) , ['class' => 'form-control', 'required']) !!}

selected value tag of Form::model doesn't bind property from Model

I'm learning Laravel and have an issue when trying to bind a property of the Model to selected values of the select tag. I tried to leave the 3rd parameter null because I believe Form Model Binding will automatically take care of it but it doesn't work. Here is what I already tried:
{{$article->tag_list}} // show [1,3]
//it doesn't work
{!! Form::select('tag_list[]', $tags, null , ['class' => 'form-control', 'multiple'] ) !!}
-------------
//it doesn't work as well
{!! Form::select('tag_list[]', $tags, $article->tag_list , ['class' => 'form-control', 'multiple'] ) !!}
-----------
//it works
{!! Form::select('tag_list[]', $tags, [1,3] , ['class' => 'form-control', 'multiple'] ) !!}
In the model I have the getTagListAttribute() which works fine.
public function getTagListAttribute(){
return $this->tags->lists('id');
}
With Text Input, the form works fine. Btw, I'm using 5.2.1 version. What am I missing here ?
I found the missing piece. the select function expects an array but getTagListAttribute() return an Collection object.
public function getTagListAttribute(){
return $this->tags->lists('id')->all();
}
or I can do this
public function getTagListAttribute(){
return $this->tags->lists('id')->toArray();
}

Multiple forms with field name arrays fail vaildation

I have multiple forms in a tabbed layout and post to the same resource controller. These fields have the same field names with a few as arrays. Use case is password storage where depending on the type of password depends on the fields needed.
Input field
<?= Form::text('name', Input::old('name'), array('class' => ($errors->has('name')) ? 'invalid' : '', 'placeholder' => 'Application Name')) ?>
<?= Form::text("data['username']", Input::old('data["username"]'), array('class' => ($errors->has('data.username')) ? 'invalid' : '', 'placeholder' => 'Username')) ?>
<?= Form::text("data['password']", Input::old('data["password"]'), array('class' => ($errors->has('data.password')) ? 'invalid' : '', 'placeholder' => 'Password')) ?>
Validation rules
protected $rules = array(
'name' => 'required',
'data.username' => 'required',
'data.password' => 'required'
);
I have more data fields but this illustrates the use case.
I get errors properly with posting with empty fields and the old input is populated but I also get errors for filled fields. My post data shows populated fields.
Tested with just one form (could have done that the first time) and still had the error. My issue here was with the how the data['username'] was used.
Should be data[username] without the quotes. While post data and everything works with the quotes, the validator was not liking it.

Resources