Required input is not working? - laravel

I have this input but its not working because i have in name []. Any suggestion how can i fix this? If i remove this [{{$language->code}}] required is working.
#foreach ($languages as $language)
<input type="text" id="text-title" name="article_title[{{$language->code}}]" value="" class="form_input" required="required">
#endforeach
<button type="submit" class="submit_property bg_green pull-right">CREATE ARTICLE</button>
validation rules:
public function rules()
{
return [
'article_title' => 'required:articles',
'slug' => 'required|unique:articles',
}
Problem is that i need required rule only if $language->id = 1

You can use Laravel's native validation of array:
$validator = Validator::make($request->all(), [
'article_title.*' => 'required',
]);

The rule will be
public function rules()
{
return [
'article_title.*' => 'required',
'slug' => 'required|unique:articles',
];
}

Related

Livewire validateOnly with validate in the same component

I have a little problem with the data validation with livewire ( laravel ).
I noticed that when I set up the validation in real time ( validateOnly() ), the information entered in the form is validated in real time. At this level everything is fine.
But when I click on the button to submit the form (even though the form contains errors), the form is unfortunately sent to my function defined in the wire:submit.
So my question is : is it possible to revalidate the information in the wire:submit method that receives the data after the form is submitted ? If so, how can I do that?
PS: I tried to set the validate method in my wire:submit function but nothing happens. It blocks the form from being submitted but it doesn't give me an error .
My source code :
<?php
class UserProfile extends Component
{
use WithFileUploads;
public $countries = [];
public $profile = [];
protected function rules() {
if ( !LivewireUpdateProfileRequest::authorize() ) {
return abort(403, "Your are not authorized to make this request !");
}
$rules = LivewireUpdateProfileRequest::rules();
if ( !empty($this->profile['phone']) ) {
$rules['profile.phone'] = [ 'required', 'phone_number:' . $this->profile['phone'] ];
}
return $rules;
}
public function mount()
{
$this->countries = Countries::all();
$this->profile = Auth::user()->toArray();
}
public function updateUserProfile()
{
$validatedData = $this->validate();
dd( $validatedData );
}
public function updated($key, $value)
{
$this->validateOnly($key);
}
public function render()
{
return view('livewire.user-profile');
}
}
Html source :
<form action="" method="POST" wire:submit.prevent="updateUserProfile">
<input name="profile.email" type="email" wire:model="profile.email" />
#error('profile.email') {{ $message }} #enderror
<input name="profile.phone" type="tel" wire:model="profile.phone" />
#error('profile.phone') {{ $message }} #enderror
</form>
Here is LivewireUpdateProfileRequest content :
<?php
namespace App\Http\Requests\Web;
use Illuminate\Foundation\Http\FormRequest;
class LivewireUpdateProfileRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public static function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public static function rules()
{
return [
'profile' => ['required', 'array', 'size:10'],
'profile.firstname' => ['required', 'string'],
'profile.lastname' => ['required', 'string'],
'profile.email' => ['required', 'email'],
'profile.phone' => ['required', 'phone_number:33'],
'profile.gender' => ['required', 'gender'],
'profile.image' => ['sometimes', 'image', 'mimes:png,jpg,jpeg'],
'profile.address' => ['required', 'string'],
'profile.city' => ['required', 'string'],
'profile.country_id' => ['required', 'exists:countries,id'],
'profile.birth_at' => ['required', 'date', 'min_age:18'],
];
}
}
Usually in your saving method you would run validation once more for all fields. The livewire docs share this example:
Livewire Component:
class ContactForm extends Component
{
public $name;
public $email;
protected $rules = [
'name' => 'required|min:6',
'email' => 'required|email',
];
public function updated($propertyName)
{
$this->validateOnly($propertyName);
}
public function saveContact()
{
$validatedData = $this->validate();
Contact::create($validatedData);
}
}
With this HTML:
<form wire:submit.prevent="saveContact">
<input type="text" wire:model="name">
#error('name') <span class="error">{{ $message }}</span> #enderror
<input type="text" wire:model="email">
#error('email') <span class="error">{{ $message }}</span> #enderror
<button type="submit">Save Contact</button>
</form>
This should validate the inputs near-realtime using the updated-method and on submit using the saveContact-method.
If you could share your code, we could debug it easier.
Source: https://laravel-livewire.com/docs/2.x/input-validation#real-time-validation

laravel select box value not adding to database

so am trying to send the value of a select box to database to calculate admin roles but it doesn't receive the value here is my view
<div class="form-group row">
<label for="exampleFormControlSelect1" class="col-md-4 col-form-label text-md-right">Role</label>
<div class="col-md-6">
<select class="form-control" id="exampleFormControlSelect1" name="role">
<option value="1">Super Admin</option>
<option value="2">Admin</option>
<option value="3">Doctor</option>
<option value="4">Sales</option>
</select>
</div>
</div>
and this is my controller its for adding new admins to the database (not users with admin roles)
public function showRegistrationForm()
{
return view('auth.admin-register');
}
public function register(Request $request)
{
// Validate form data
$this->validate($request,
[
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:admins'],
'password' => ['required', 'string', 'min:8'],
'role' => ['required']
]
);
dd($request->role);
// Create admin user
try {
$admin = Admin::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
'role' => $request->role
]);
return redirect()->route('admin.dashboard');
} catch (\Exception $e) {
return redirect()->back()->withInput($request->only('name', 'email'));
}
}
the dd($request->role) works and return the nvalue of the but the problem is with the
try {
$admin = Admin::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
'role' => $request->role
]);
In model you can define protected columns then all the other column will be auto fillable
or you can define fillable columns in model
The problem was that I didn't set the role in fillable in admin model

Field is required when other three fields are empty

I have 4 input fields. 1 of them has to be filled.
My fields :
<input name="name" placeholder="Name">
<input name="hair_style" placeholder="Style">
<input name="hair_color" placeholder="Color">
<input name="options" placeholder="Options">
My function
$this->validate($request, [
'name' => 'required_if:hair_style,0,',
]);
So when hair_style is 0. Input field name has to be filled. This works but.. I want it like this below but I don't know how:
$this->validate($request, [
'name' => 'required_if:hair_style,empty AND hair_color,empty AND options,empty,',
]);
It has to work like this. When hair_style, hair_color and options are empty name has to be filled. But is this possible with required_if ?
You can try as:
'name' => 'required_if:hair_style,0|required_if:hair_color,0||required_if:options,0',
Update
You can conditionally add rules as:
$v = Validator::make($data, [
'name' => 'min:1',
]);
$v->sometimes('name', 'required', function($input) {
return ($input->hair_style == 0 && $input->hair_color == 0 && $input->options == 0);
});
You can add more logics in the closure if you required...like empty checks.
So all I had to do was :
$this->validate($request, [
'name' => 'required_without_all:hair_style, hair_color, options',
]);
for more information check https://laravel.com/docs/5.3/validation#rule-required-without-all

How to apply a validation rule to every element present within an array?

How to apply validation rules to every item within an items[] array? For example:
...->validate($request, [
'items[]' => 'required' // <-- what is the correct syntax?
]);
Try something like this
$validator = Validator::make($request->all(), [
'person.*.email' => 'email|unique:users',
'person.*.first_name' => 'required_with:person.*.last_name',
]);
Where person is the name of the input field and email is the key
Laravel 5.2 has an array validation all you need to do is :
In your view assuming that you have an inputs like this :
<input type="text" name="example[]" />
<input type="text" name="example[]" />
The [] are the key for this :)
And in your controller you can just do :
$this->validate($request, [
'example.*' => 'required|email'
]);
$this->validate($request, [
'items' => 'required|array',
'items.*.title' => 'required',
]);

Solving Method Not Allowed Http Exception in Laravel 5.2

I want some values in my table editable, so I created this simple custom form. But this will throw error of method not allowed http exception.Any help?
<form action="{{ url('/idx-test/update-this-student/'. $student->id)}}" class="" method="POST">//changing this to put, patch does not solve the error
Route
Route::post('/idx-test/update-this-student/{id}', 'StudentController#updateThisStudent'); //again changing this to patch,or put does not help
Controller
public function updateThisStudent(StudentRequest $request, $id)
{
$student = Student::findOrFail($id);
$student->update($request->all());
// return redirect('city');
echo "updated";
}
StudentRequest
public function rules()
{
return [
'firstname' => 'required|alpha|min:2|max:10',
'lastname' => 'required|alpha|min:2|max:10',
'bday' => 'required|date',
'address' => 'required|min:10',
'zip' => 'required|min:4|max:10',
'phone' => 'required|digits:7',
'mobile' => 'required|digits:11',
'email' => 'required|email',
'city_id' => 'required',
'yearlevel_id' => 'required',
'section_id' => 'required',
];
}
By adding this small piece of code
<input type="hidden" name="_method" value="PATCH">
My problem solve

Resources