I have a project that consists of multilingual functionality. So I'm creating a form that consists of multiple languages to be inserted if User wants.
But validation should be like if any of the fields having the same name consist value then leave rest one like as
Form
<form>
<input type="text" name="name[EN]" />
<input type="text" name="name[AR]" />
<input type="text" name="name[FR]" />
<input type="submit" value="submit" />
</form>
Now I want to validate that if any one of these fields have value then submit form else throw a validation
So I've tried Laravels required_if, but it didn't work.
public function rules()
{
return [
'name.*' => 'required_if:name,1',
];
}
So how to make such validation in laravel
I've searched but could not find a built in way of doing this. You can create your own rule using
php artisan make:rule NonEmptyFiltered
and then define the rule as:
class NotEmptyFiltered implements Rule {
public function passes($attribute, $value) {
return !empty(array_filter($value));
}
public function message() {
return ':attribute must have at least one non-null element';
}
}
You can then do:
public function rules()
{
return [
'name' => [ new NonEmptyFiltered() ]
];
}
I believe this should do the trick:
$rules = [
'name.EN' => 'required_without_all:name.AR,name.FR',
'name.AR' => 'required_without_all:name.EN,name.FR',
'name.FR' => 'required_without_all:name.EN,name.AR',
];
The rule makes the field to be required if the other fields are empty https://laravel.com/docs/5.6/validation#rule-required-without-all.
Related
In my controller, I validate the input fields and if any validation fails I want to return back to the form and refill the previous values that the user was inputing (if there is any other easier way instead this please tell me). But here is what I'm doing:
Controller.php:
public function store(Request $request, AnexoController $anexoController)
{
$validator = Validator::make(
$request->all(),
$rules,
$messages
);
if($validator->fails())
{
return Redirect::to($request->headers->get('referer'))
->withErrors($validator)
->withReq($request->all());
}
// continues the function...
}
At the view.blade.php:
<input type="text"
maxlength="256"
id="text-input"
name="id"
placeholder="Código"
class="form-control"
#if(isset($req)) value="{{$req->id}}"
#else value="$REQ VARIABLE NOT SET"
#endif
required>
And when I test it, the field id value is set to "$REQ VARIABLE NOT SET" but $errors from $validator variable is set. So, why isn't the variable $req being set in this context? Thanks in advance.
Use this
$request->validate([
//rules
]);
It will automatically return to form page with all the errors and inputs,
In your form you'll neet do add a helper in value of inputs for old inputs
<input type="text" value={{ old('email')}} name="email">
see https://laravel.com/docs/5.8/validation & https://laravel.com/docs/5.8/helpers
Here is my case, I got a Request Class which I create using artisan :
php artisan make:request StoreSomethingRequest
Then I put my rules there, and then I can use it in my Controller method like this:
public function store(StoreSomethingRequest $request)
{
}
But what I need is, I want to separate 2 Request logic based on the button in my view (Assumes there is more than 1 submit button in my view). So my controller will look like this :
public function store(Request $request)
{
if($request->submit_button === 'button1')
{
// I want to validate using StoreSomethingRequest here
}
else
{
// I dont want to validate anything here
}
}
I would appreciate any suggestion / help. Please. :D
You can use something like this in your request class inside rules method.
public function rules()
{
$rules = [
'common_parameter_1' => 'rule:rule',
'common_parameter_2' => 'rule:rule',
];
if($this->submit_button === 'button1')
{
$rules['custom_parameter_for_button_1'] = 'rule:rule';
}
else
{
$rules['custom_parameter_for_button_2'] = 'rule:rule';
}
return $rules;
}
Add name and value attributes on the HTML submit buttons. Then check which one has been submitted. Example:
<button type="submit" name="action" value="button1">Save 1</button>
<button type="submit" name="action" value="button2">Save 2</button>
Then in the handler:
If (Request::input('action') === 'button1') {
//do action 1
} else {
// do action 2
}
I am learning/using Laravel5 and using the Request generator tool to make a custom request validation handler;
php artisan make:request <nameOfRequestFile>
And I find that my validation always passes, but I don't know why.
On my view I do a vardump of the errors;
{{ var_dump($errors) }}
And when I submit an empty form it always inserts a new record, when it should fail.
The var dump reports;
object(Illuminate\Support\ViewErrorBag)#135 (1) { ["bags":protected]=> array(0) { } }
Which seems to suggest the error bag is always empty.
My request file is pretty simple
namespace App\Http\Requests;
use App\Http\Requests\Request;
class PublishDriverRequest extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'name.required|min:3' => 'Please provide a name.',
'companyName.required|min:3' => 'Please provide a company name.'
];
}
}
I checked my input form and the names are the same;
<input type="text" name="name" id="name" class="form-control">
<input type="text" name="companyName" id="companyName" class="form-control">
And I checked my database, the names are the same too.
My controller when storing the data is equally straight forward;
public function store(PublishDriverRequest $request) {
Driver::create($request->all());
return redirect('/');
}
So I'm not sure why the validation always passes; if I submit an empty form it should fail as the rules indicate minimum length and required.
What am I doing wrong?
Change you validation rules to:
public function rules()
{
return [
'name' => 'required|min:3',
'companyName' => 'required|min:3',
];
}
To show custom validation error:
public function messages()
{
return [
'name.required' => 'Please provide a name.',
'companyName.required' => 'Please provide a company name.',
];
}
Note: Use message() method before rules()
I'm using (and loving) the Laravel 5 form request validation so far. But now I'm stuck trying to validate related models.
Say I have a Car model which has many Wheel models and I'd like to validate a new car. In the CarController#store method I'm using the following to validate the car, but this does of course not validate the wheels.
public function store(StoreCarRequest $request)
{
// Create the car
}
What needs to be done to validate the Wheels of a Car? Can this be done with form request validation?
Edit
I'm getting closer. The remaining issue is that I need to iterate through the wheels which are stored in an array (because the HTML input name is e.g. wheels[0][color]), but the validator is searching for a color field, not wheels[0][color].
public function store(StoreCarRequest $r)
{
// Validate the wheels
foreach ($r->input('wheels') as $wheel)
{
// TODO: use $wheel somewhere?
$snr = new StoreWheelRequest;
$this->validate($r, $snr->rules()); // Validation fails: 'color' field is required
}
// Validation passed, create the car (and the wheels)
}
StoreCarRequest.php
public function rules()
{
return [
'engine' => 'required',
'seats' => 'required',
];
}
StoreWheelRequest.php
public function rules()
{
return [
'color' => 'required',
];
}
The HTML form
<form method="POST" action="...">
<input type="text" name="engine">
<input type="text" name="seats">
<input type="text" name="wheels[0][color]">
<input type="text" name="wheels[1][color]">
<input type="text" name="wheels[2][color]">
<input type="text" name="wheels[3][color]">
<input type="submit" value="Create">
</form>
After some more Googling, I stumbled upon the following article: http://ericlbarnes.com/laravel-array-validation/
It boils down to adding rules dynamically inside the rules() method by iterating over the input array.
You can use dot notation to validate nested arrays :
public function rules()
{
return [
'engine' => 'required',
'seats' => 'required',
'wheel.color' => 'required',
];
}
I'm having problem saving data to the database since catch exception is always being called. try always get ignored. I don't really know what's happening. I've been working for this for hours and I can't get it to work. I'm using kohana 3.3 and kostache.
So here's the controller.
Controller
APPATH/classes/controller/album.php
public function action_create()
{
$view = Kostache_Layout::factory();
$layout = new View_Pages_Album_List();
$album = ORM::factory('Album_Information');
$album_name = $this->request->post('inputAlbum');
$artist = $this->request->post('inputArtist');
$album->Album_Name = $album_name;
$album->Artist = $artist;
try
{
$album->save();
HTTP::redirect('album');
}
catch(ORM_Validation_Exception $e)
{
$layout->errors = $e->errors('models');
}
}
$this->response->body($view->render($layout));
}
Templates
APPATH/templates/pages/album/list.mustache
<h3>Add A New Album</h3>
<form action="album/create" method="post">
<label for="inputAlbum">Album Name:</label>
<input id="inputAlbum" type="text" name="inputAlbum" /><br />
<label for"inputAlbum" class="error">{{#errors}}{{inputAlbum}}{{/errors}}</label>
<label for="inputArtist">Album Artist:</label>
<input id="inputArtist" type="text" name="inputArtist" /><br />
<label for="inputArtist" class="error">{{#errors}}{{inputArtist}}{{/errors}}</label>
<input type="submit" name="submit" value="Add" />
</form>
Model Rules
APPATH/classes/model/album/information.php
class Model_Album_Information extends ORM
{
protected $_primary_key = 'ID';
protected $_table_name = 'album_information';
public function rules()
{
return array(
'inputAlbum' => array(
array('not_empty'),
),
'inputArtist' => array(
array('not_empty'),
),
);
}
Messages
APPATH/messages/models/album.php
return array(
'inputAlbum' => array(
'not_empty' => ':You must provide Album Name',
),
'inputArtist' => array(
'not_empty' => ':You must provide Album Artist',
),
);
The errors are showing when there's no input on the input field when i hit on the submit button, no problem with that, but even there's an input the errors are still being shown. So catch is always being called. When i remove try and catch I can easily save data to the database but there's no validation.
Thank you and more power.
You expect the ORM class to magically know the value of $album->Album_Name came from a HTTP form input named inputAlbum. It won't.
Create rules for the Album_Name and Artist properties of the ORM object itself. Not the possible input method.
The Controller knows what data to pass to models. The Model is only concerned with the data it received. Not where it came from.