I have many fields on my form.
2 of them have to bind together.
The first is an datepicker and the second a select field (filled in function of date chosen).
<input class="form-control pull-right" name="day_desired" id="day_desired" placeholder="Day Desired" type="text" value="{{ old('day_desired') }}">
<select id="hour_id" name="hour_id" class="form-control">
<option value="0">--- Choose hour ---</option>
<option value="10:00">10h00</option>
...
</select>
So I want to do this :
If no date chosen, these 2 fields are optionals.
If a date is chosen, the select field is required and not equal to 0 (0 is the first value of options and I use it like a label).
I had many tests with required_if, required_unless no success....
return [
'name'=>'required',
'first_name' =>'required',
...
'day_desired' =>'nullable',
'hour_id' =>'nullable'
];
Thank you very much
The required_if and required_unless checks will look for a certain condition for the value of another field. That is not what you need here.
You can use required_with:
'day_desired' =>'nullable',
'hour_id' =>'required_with:day_desired|nullable|min:1'
The reason that hour_id has to be nullable is that you don't want the min:1 check to run when the day_desired and the hour_id are empty. Still, the required_with rule will fail, even though the field is nullable, as pointed out in this post on GitHub. This behaviour was added in this release: https://github.com/laravel/framework/releases/tag/v5.4.16.
Related
I am trying to store specific value in laravel. Here Select User not required field but in foreach loop hidden field proj_id must has value. Suppose there are 5 rows and I want to store only 2nd and 5th user along with proj_id from hidden field. Here I want to mention that in controller I also kept delete operation so that I can remove previously inserted SAME PROJECT ID related record. For example If I want to store 2nd and 3rd user, that time only 2nd and 3rd users record will remove first then insert. In my code there are logical error but could not find solution. Thanks in advance
<form action="{{ url('/save-project') }}" method="POST">
<tr>
#foreach($projects as $val)
<td>
<input type="hidden" name="proj_id[]" value="{{$val->id}}">
<select name="user_id[]">
<option value="">Select User</option>
<option value="2">x</option>
<option value="4">y</option>
</select>
</td>
#endforeach
</tr>
<input type="submit">
</form>
Controller
$countUserID = count($user_id);
assign_project::where('flag','Y')
->WhereIn('proj_id',$request->proj_id)
->delete();
for($i=0;$i<$countUserID;$i++){
$assign_project = new assign_project();
$assign_project->proj_id = $request->proj_id[$i];
$assign_project->user_id = $request->user_id[$i];
$assign_project->save();
}
JSON fields are gaining more popularity since they became officially supported in MySQL 5.7.8. Even the popular Spatie Laravel Medialibrary package use them, so why shouldn’t we?
To create a JSON field, all we need to do in Laravel migration is use ->json() method:
$table->json('array_data');
Next, you need to tell your model to cast that column from JSON to an array automatically:
class Product extends Model
{
protected $casts = [
'array_data' => 'array'
];
}
This way, you will receive $array_data as array and don’t need to do json_decode() at all.
I have a form with some fields which I want to validate using Laravel's validate() method.
public function postSomething(Request $req) {
...
$this->validate($req, [
'text_input' => 'required',
'select_input' => 'required'
]);
...
}
The issue is that if the form is submitted without selecting an option from the select input it is ignored in the request and Laravel doesn't validate it despite the fact that it is added to the ruleset with the required validation rule. Empty text inputs are being validated correctly.
+request: ParameterBag {#42 ▼
#parameters: array:1 [▼
"text_input" => ""
"_token" => "TCDqEi2dHVQfmc9HdNf8ju1ofdUQS6MtDBpUMkl7"
]
}
As you can see, the select_input is missing from request parameters if it was left empty.
Here is the HTML code for my select input:
<select class="form-control" name="select_input">
<option disabled selected>Please select...</option>
<option value="val1">Value 1</option>
<option value="val2">Value 2</option>
</select>
Is there a way to make the validation work for all fields from the ruleset even if some of them are not present in the request?
From Laravel 5.1 validation documentation:
required
The field under validation must be present in the input data and not empty. A field is considered "empty" is one of the following conditions are true:
The value is null.
The value is an empty string.
The value is an empty array or empty Countable object.
The value is an uploaded file with no path.
P.S. I'm using Laravel 5.1, so present method is not available.
Your html should look like this
<select class="form-control" name="select_input">
<option value="" selected >Please select...</option>
<option value="val1">Value 1</option>
<option value="val2">Value 2</option>
</select>
$this->validate($req, [
'text_input' => 'required',
'select_input' => 'required',
]);
If your select box values are integer then
you can use required with integer like
$this->validate($req, [
'text_input' => 'required',
'select_input' => 'required|integer',
]);
Or if you have limited options for that select box then you can use
'select_input' => "required|in:val1,val2,val3",
You made it's option disabled, so it won't send anything through your form.
Change your select box to
<select class="form-control" name="select_input">
<option value="">Please select...</option>
<option value="val1">Value 1</option>
<option value="val2">Value 2</option>
</select>
There are few options I can recommend:
Manually validate the request without using the validation extended in the Controller, I.e:
//validator FACADE
$ validator = Validator::make ($request->all(), [
// rules here
]);
By this you can monitor which fields are passed and which one are not passed.
Secondly, set a default value for the select list and check that value when you are validating in the Controller, that is, if you have this default value then nothing is selected. You definitely will have only the fields submitted in your Controller.
I'm trying to use blade to display a dropdown list from table data. The problem I have, is that I want to display the results of two fields in the table concatenated, not just one.
So I want something to render something like;
<select id="agreement_type" name="agreement_type">
<option value="1">Agreement Field 1 - Agreement Field 2</option>
<option value="2">Agreement Field 1 - Agreement Field 2</option>
<option value="4">Agreement Field 1 - Agreement Field 2</option>
</select>
My controller currently looks like this;
$agreements = Agreement::lists('agreement_type','id');
return View::make('client_agreements.create')
->with('agreements', $agreements);
My blade view currently looks like this;
<div class="form-group">
{{ Form::label('agreement_type', 'Agreement type') }}
{{ Form::select('agreement_type', $agreements) }}
</div>
I have tried to amend the view and controller in various ways to get the desired output. But can't get it to work.
I want to display agreement_type and level and have the id set as the value so I tried;
$agreements = Agreement::lists('agreement_type'.'level','id');
But this just displays level as the value and completely ignores id.
This is the simplest method. Just use a foreach loop to build the options array:
$agreements = Agreement::all();
$agreementOptions = array();
foreach($agreements as $agreement){
$agreementOptions[$agreement->id] = $agreement->agreement_type.' '.$agreement->level;
}
return View::make('client_agreements.create')
->with('agreements', $agreementOptions);
However you can also define an attribute accessor in your model. You can use that to create new properties that can be accessed normal, but you can run logic to generate them (like combining to attributes)
public function getSelectOptionAttribute(){
return $this->attributes['agreement_type'].' '.$this->attributes['level'];
}
And then you can use lists:
$agreements = Agreement::all()->lists('select_option', 'id');
(Laravel converts SelectOption (studly case) from the method name to select_option (snake case) for the attribute, so don't get confused by that)
I am using this multiselect dropdown plugin . I can get all the ids of the selected items in the dropdown during the store method. However during the edit method when ever i am trying to load the entity that has multiple values , i am unable to mark the items as checked in the dropdown.
so for example -
Suppose I am working with Contacts. Each contact can belong to many categories. There is a belongsToMany relationship between the contacts and the categories. Whenever I am adding a new contact (and if the user has selected many categories) i get the id of all the categories and assign it to the contact. Now when I am trying to load the contact again, i have to display the list of categories that were selected for this contact - which i have ben unable to do so till now.
Travis answers really helped me a lot. Hence I am marking this as the correct answer. However there were some updates that I had to do . Following is what I had to do ..
#if(isset($contact))
<?= Form::select(
'category_ids[]',
Category::lists("name", "id"),
$contact->categories()->select('categories.id AS id')->lists('id'),
[
'class' => 'form-control multiselect',
'multiple'
]
)?>
#else
{{ Form::select("category_ids[]", Category::lists("name", "id"), Input::old("category_id"), array( "class" => "form-control multiselect" , "multiple" => "multiple" )) }}
#endif
I am using the same form for the create and edit operations , so in the create form , it was throwing me an error on the contact->categories line which is true because in the create method the contact is null. Hence the check.
Here's how I accomplish multi-selects in Laravel 4:
<?= Form::select(
'category_ids[]',
App::make('Category')->lists('name', 'id'),
$contact->categories()->select('categories.id AS id')->lists('id'),
[
'class' => 'form-control',
'multiple'
]
)?>
The resulting select markup looks like this:
<select class="form-control" multiple="multiple" name="category_ids[]">
<option value="1" selected="selected">category 1</option>
<option value="2">category 2</option>
</select>
And then, when you update, you'll need to add this line after validating your model:
$contact->categories()->sync(Input::get('category_ids'));
Use this in both your create and edit forms. In your create action,
$contact->categories() will be empty, so the select will not be populated, but in the edit action, you will get the properly selected values.
Edit: In order to share the form like this, you'll need to pass in a new instance of the contact model in your create action like so:
public function create()
{
$contact = App::make('Contact');
return View::make('contact.create', concat('contact'));
}
In your shared form, $contact will always be available even if it's not yet persisted.
I have a problem with laravel, and my form.
In my form (createBand.blade.php), i made a form with a dropdownlist wich call a database table: musicalGenre.
It should be noted that the dropdownmenu/list (select form) calls to another table in the database called MusicalGenre, and the form where I want the dropdownlist is to register a band in the database table Bands.
The select form works, i could choose in a dropdownlist all musicalGenre_name in my table after seeding them. Here's the blade page code (of course i have open, close the form and the section like laravel requires):
<p>
{{Form::label('name','Name of the Band: ')}}
{{Form::text('name',Input::old('name'))}}
</p>
#if ($errors->has('name'))
<p class='error'> {{ $errors->first('name')}}</p>
#endif
<br>
<br>
<p>
{{Form::label('email','Band Email: ')}}
{{Form::text('email',Input::old('email'))}}
</p>
#if ($errors->has('email'))
<p class='error'> {{ $errors->first('email')}}</p>
#endif
<br>
<br>
<p>
{{Form::label('musicalGenre','your style: ')}}
{{Form::select('musicalGenre_name', $genre_options = array('' => 'select your style') + musicalGenre::lists('name'), Input::old('musicalGenre_name')) }}
</p>
#if ($errors->has('musicalGenre'))
<p class='error'> {{ $errors->first('musicalGenre_name')}}</p>
#endif
<br>
<br>
I have a controller named createBandController, where i made some rules for validators for the blade form. The poblem is:
i can't pass the validators, that is to say, even if i choose a musical genre in my dropdownlist, for laravel there no choice made.
I have the error "musical genre is required". I don't understand the validator rules for a select form in my controller, or i don't know what i'm suposed to input in the rules for musical genre. Here's the controller code:
public function createBand() {
$result = MusicalGenre::all();
$genre = $result->lists('name');
$inputs = Input::all();
$rules = array(
'name' => 'required|between:1,64|unique:bands,name',
'email' => 'between:1,128|email|unique:bands,email',
'musicalGenre' => 'integer|required|in:musicalGenre'
);
$validation = Validator::make($inputs, $rules);
if ($validation->fails()) {
return Redirect::to('createBand')->withInput()->withErrors($validation)
->with('alert_error', 'you have some mistakes');
Don't pay attention to the names, (i'm french, i changed them in order to be clear for you), and i'm sure that is the validator of my dropdownlist who make problems when i fill out my form, because i can't pass it. In my original project code, there are no spelling mistakes.
All my validators and variable names work. I think i need to find the correct rules for a select form input and validators in order to laravel knows i made a choice when i choose in my dropdownlist.
At first i thought to specify that the dropdownlist use the database table musicalGenre. Like i specified that some fields are in the database table Bands, like this:
'name' => 'required|between:1,64|unique:bands,name'
Here, "name" is a field of the database table Bands. But it didn't work too.
If anyone have a solutions or wants to help, i'm interested.
Thank you (and sorry if my english seems so bad).
The validation rule in: on the field musicalGenre won't work the way that you have implemented it. It expects a comma delimited list of strings which the field value is scrubbed against.
For example if the field was 'Gender' the validation would be:
'gender' => 'in:male,female'
To validate against musicalGenre against a model you will need to write a custom Validator. See http://laravel.com/docs/validation#custom-validation-rules
I am currently writing a custom validator for this 'belongs_to' validation and when I have it working I'll post it here.
UPDATE
I have written a custom validation rule that should help. Firstly create a validators.php file and include it in global.php
require app_path().'/validators.php';
Within validators.php create the custom rule:
Validator::extend('exists_in', function($attribute, $value, $parameters)
{
$result = $parameters[0]::find($value);
return ($result == null) ? FALSE : TRUE;
});
In your validations you could now have:
'musicalGenre' => 'integer|required|exists_in:musicalGenre'
The exists_in validation takes a parameter of the Model Class name
And to give this validation an error message, add the following to the array in app/lang/en/validation.php:
"exists_in" => "The selected :attribute is invalid."
Does exists:musicalGenre instead of in:musicalGenre help?