button still disabled even if the form is filled - php

I tried to create a few tricks for my form "if the form fields is null or empty the submit button should be disabled".
I do this by using livewire but in my case the button it still disabled even if the form fields is filled.
livewire file :
<?php
namespace App\Http\Livewire;
use Livewire\Component;
class ExampleForm extends Component
{
public $name = '';
public $email = '';
public $password = '';
public $disabled = true;
protected $rules = [
'name' => 'required|min:6',
'email' => 'required|email',
'password' => 'required|min:6',
];
public function updated($fields)
{
$this->validateOnly($fields);
if(!is_null($fields) && !empty($fields)) {
$this->$disabled = false;
} else {
$this->$disabled = true;
}
}
public function submitForm()
{
$validatedData = $this->validate();
Example::create($validatedData);
}
public function render()
{
return view('livewire.example-form');
}
}
in blade.php
<form wire:submit.prevent="submitForm">
<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
<input type="password" wire:model="password">
#error('password') <span class="error">{{ $message }}</span> #enderror
<button type="submit" {{ $disabled ? 'disabled' : '' }}>Submit</button>
</form>

Updated answer
As per the requirement now, the disabled property should be set to false only if all the validation passes for the required fields.
public $disabled = true;
public function updated($fields)
{
$this->disabled = true;
$this->validate(); // this is a blocking call
$this->disabled = false; // execution will reach this line only if all passes the validation.
}
Note that, the $fields property passed through only has the currently updated property. so we cannot use it to validateOnly method, since it will only validate the passed property.

Related

Livewire array validation not rendering the errors

Livewire validation of array inputs is not rendering
class TravelDetail extends SlideOver
{
public $existed_visa_name = []; //an array input
}
protected $rules = [
'existed_visa_name.*' => 'required|min:6'
];
public function save()
{
$this->validate(); // validating here
return;
}
blade file
<input type="text" class="form-control form-control-solid ps-13" placeholder="{{ __('Visa Name') }}" wire:model.defer="existed_visa_name.{{ $key }}">
#error('existed_visa_name.{{ $key }}') <span class="error">{{ $message }}</span> #enderror
<!--It is in the loop and $key = 0 -->
Try this instead. Let me know if it works.
#error('existed_visa_name.' . $key).
Source Laracast question

Laravel livewire Login resulting in 302 Found

I recently added livewire login component on a multi tenant website. Normal laravel login and registration works completely fine but when through livewire i click submit Login page Post request results in 302 found and redirects to a Login route GET request
<?php
namespace App\Http\Livewire;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
class Login extends Component
{
public $email;
public $password;
protected $rules = [
'email' => 'required|email',
'password' => 'required',
];
public function submit(){
$data = array(
'email' => $this->email,
'password' => $this->password
);
return $data;
$validatedData = $this->validate();
if (Auth::attempt($data)) {
return redirect('/');
} else{
return "error";
}
}
public function render()
{
return view('livewire.login');
}
}
Livewire form
<div>
<form wire:submit.prevent="submit">
<input type="email" class="form-control form-control-lg" wire:model="email">
#error('email') <span class="error">{{ $message }}</span> #enderror
#csrf
<input type="password" class="form-control form-control-lg" wire:model="password">
#error('password') <span class="error">{{ $message }}</span> #enderror
<button type="submit" class="btn btn-lg btn-primary btn-block">Login</button>
</form>
</div>
I have a temporary solution by entering 'livewire/message/login' in VerifyCsrfToken.php
I'm not sure why livewire isn't able to fetch the csrf token from head tag
<meta name="csrf-token" content="{{ csrf_token() }}">
what could be the reason
Your submit() method returns $data, which means no line of code will get executed after return statement.
public function submit(){
$data = array(
'email' => $this->email,
'password' => $this->password
);
return $data;
// Below code will never get executed
$validatedData = $this->validate();
if (Auth::attempt($data)) {
return redirect('/');
} else{
return "error";
}
}
You are not validating data at all.

How do I redirect to another page after form submission in Laravel

form
When i submit the form it redirects back to the form itself, can anyone help me?
<form action="/jisajili" method="POST">
#csrf
<div class="card-panel z-depth-5">
<h5 class="center red-text">Jiunge Nasi</h5>
<div class="input-field">
<i class="material-icons prefix">account_circle</i>
<input type="text" name="username" class="validate">
<label>Jina lako</label>
</div>
<div class="input-field">
<i class="material-icons prefix">phone</i>
<input type="number" name="phone" class="validate">
<label>Nambari ya simu</label>
</div>
....
</p>
<input type="submit" name="submit" value="Jiunge" class="btn left col s12 red">
Controller
class registration extends Controller{
public function create(){
return view('jisajili.jiunge');
}
public function store(Request $request){
$reg = new regist;
$reg->jina = $request->input('username');
$reg->simuNumber = $request->input('phone');
$reg->email = $request-> input('email');
$reg -> password = bcrypt($request->input('password'));
$cpassword = $request -> input('cpassword');
$reg->save();
$validated = $request->validate([
'name' => 'required|unique:posts|max:10',
'body' => 'required',
]);
return redirect('home');
}
}
What I would do is first check for the data requirements before you add the object to the database. Also I would add the columns of the models into the Model file to use the Object::create function with an array parameter.
I recomment to use routing in your blade file. I noticed you used action="/route". What you want to do is naming your routes with ->name('route_name') in the route files. To use them in your blade files with the global route function route="{{ route('route_name') }}".
<?php
class PostController extends Controller
{
public function index()
{
return view('post.create');
}
public function store(\Illuminate\Http\Request $request)
{
$validator = Validator::make(
$request->all(),
[
'name' => 'required|unique:posts|max:10',
'body' => 'required'
]
);
// Go back with errors when errors found
if ($validator->fails()) {
redirect()->back()->with($validator);
}
Post::create(
[
'name' => $request->get('name'),
'body' => $request->get('body')
]
);
return redirect()
->to(route('home'))
->with('message', 'The post has been added successfully!');
}
}
What you can do after this is adding custom errors into the controller or add them into your blade file. You can find more about this in the documentation of Laravel.
it redirects you back because of validation error.
change password confirmation name from cpassword into password_confirmation as mentioned in laravel docs
https://laravel.com/docs/7.x/validation#rule-confirmed
update your controller into:
public function store(Request $request){
$validated = $request->validate([
'username' => 'required',
'phone' => 'required',
'email' => 'required',
'password' => 'required|confirmed'
]);
$reg = new regist;
$reg->jina = $request->input('username');
$reg->simuNumber = $request->input('phone');
$reg->email = $request-> input('email');
$reg -> password = bcrypt($request->input('password'));
$reg->save();
return redirect('home');
}
in your blade add the following to display validation errors:
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif

how to fix error laravel 7 array to conversion

in blade code
<div class="form-group col-md-11">
<input id="title" type="text" class="form-control #error('title') is-invalid #enderror" name="title[]"
id="title_input" value="{{ old('title') }}" autocomplete="name" autofocus
placeholder="Masukan Title">
</div>
in controller code
public function insert(Request $request){
$data = $request->all();
if(isset($request->title) && $request->title){
foreach ($data['title'] as $key => $value) {
$faqs = new Faqs();
$faqs->title = json_encode($value);
$faqs->description = $request->description;
$faqs->course_id = $request->course_id;
$faqs->save();
}
}
dd($faqs);
}
in model code
class Faqs extends Model
{
protected $table = 'faqs';
protected $fillable = ['title', 'description', 'course_id'];
public function courses()
{
return $this->belongsTo(Course::class);
}
}
I want to enter the title of more than one data, when I code it above, there is an error like this. How do I fix the error?
ErrorException
Array to string conversion.

Form array validation Laravel 5.2

I am currently stuck on solving this problem. I am new to Laravel and the MVC framework. I am struggling to create the dynamic form that gives the user the ability to add as many forms as possible. When the user enters the page at first it generates 5 form fields . Here is a look at my code so far.
<div id ={{$id = "from".$i}} >
<div class="form-group col-md-6">
<div class="col-md-6 form-group">
<label for={{$id = "Address".$i}}>Address</label>
<input type="text" name = "address[{{$i}}]" class="form-control" id={{$id = "Address".$i}} placeholder="Street Address"> <!-- problem form array how does this work in laravel -->
</div>
<div class="form-group col-md-6">
<label for={{$id = "city".$i}}>City</label>
<input type="text" value = "{{ old('city') }}" class="form-control" id={{$id = "City".$i}} placeholder="City">
#if ($errors->has('city'))
<span class="help-block">
<strong>{{ $errors->first('city') }}</strong>
</span>
#endif
</div>
How would I go about validating a form in Laravel 5.2 with from array
here's my controller
public function Postdata(Request $request) {
$this->validate($request->all(), [
'address.*' => 'required|string',
'city' => 'required',
]);
}
I am using a for loop to generate the forms dynamically.
here is the error I get
ErrorException in ValidatesRequests.php line 49:
Argument 1 passed to App\Http\Controllers\Controller::validate() must be an instance of Illuminate\Http\Request, array given, called in
C:\wamp\www\Dynamic- 1.0\app\Http\Controllers\propContoller.php on line 34 and defined
Can someone please help or point me in the right direction thank you !
add name="city[{{$i}}]"
Create a specific request with php artisan make:request PostRequest
Change public function Postdata(Request $request) { to public function Postdata(PostRequest $request) {
Remove the validate function call from your controller
Go to /app/Http/Requests/PostRequest.php
Then edit the rules function to something like this ...
.
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
$rules = [];
foreach($this->request->get() as $key => $val)
{
$rules['address.' . $key] = 'required';
$rules['city.' . $key] = 'required';
}
return $rules;
}
Thank You man ! this is the solution I end up with
<div class="form-group col-md-6">
<div class="col-md-6 form-group">
<label for={{$id = "Address".$i}}>Address</label>
<input type="text" name="address[{{$i}}]" class="form-control" id={{$id = "Address".$i}} placeholder="Street Address">
</div>
in post request i did this
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules() {
$rules = [];
foreach($this->request->get('address') as $key => $val) {
$rules['address.'.$key] = 'required';
}
return $rules;
}

Categories