Why does this code Fail once i add validation in laravel 8? - laravel

I am just starting to learn Laravel and I am a little lost here. This code works without validation.
The task is to build a website with user registration Posting data to an already existing database. As I have pointed, without validation it works just fine but when i add validation it fails.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Member;
class RegController extends Controller
{
public function store(Request $request) {
Member::create([
'fname' => $request ->fname,
'lname' => $request ->lname,
'gender' => $request ->gender,
'msisdn' => $request ->msisdn,
'email' => $request ->email,
'status' => $request ->mstatus,
'no_of_children' => $request ->kids,
'occupation' => $request ->profession,
'age' => $request ->age,
'bna' => $request ->bna,
'residence' => $request ->residence,
]);
return redirect('/members/register');
}
}
But this doesn't...
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Member;
class RegController extends Controller
{
public function store(Request $request) {
$request->validate([
'fname' => 'required',
'lname' => 'required',
'gender' => 'required',
'msisdn' => 'required|unique:members_tbl',
'email' => 'required|unique:members_tbl',
'status' => 'required',
'kids' => 'required',
'profession' => 'required',
'age' => 'required',
'bna' => 'required',
'residence' => 'required',
],
[
'fname.required' => 'Please Enter your First Name',
'lname.required' => 'Please Enter your Last Name',
'gender.required' => 'Please Enter your Gender',
'msisdn.required' => 'Please Enter your Phone Number',
'msisdn.unique' => 'A user has already registered with the phone Number',
'email.unique' => 'A user has already registered with the email',
'email.required' => 'Please enter a valid email address',
'status.required' => 'Please Let us know your marital status',
'kids.required' => 'Please fill out this field',
'profession.required' => 'Please fill out this field',
'age.required' => 'Please fill out this field',
'bna.required' => 'Please fill out this field',
'residence.required' => 'Please let us know where you live',
]);
Member::create([
'fname' => $request ->fname,
'lname' => $request ->lname,
'gender' => $request ->gender,
'msisdn' => $request ->msisdn,
'email' => $request ->email,
'status' => $request ->mstatus,
'no_of_children' => $request ->kids,
'occupation' => $request ->profession,
'age' => $request ->age,
'bna' => $request ->bna,
'residence' => $request ->residence,
]);
return redirect('/members/register');
}
}
What am i missing? The code works well without the validation but just redirects back to the form when validation is added.
Here is my Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Member extends Model
{
use HasFactory;
public $timestamps = false;
protected $table="members_tbl";
protected $fillable =[
'fname',
'lname',
'gender',
'msisdn',
'email',
'status',
'no_of_children',
'occupation',
'age',
'bna',
'residence'
];
}
This is the result of var_dump($request)
public 'request' =>
object(Symfony\Component\HttpFoundation\InputBag)[44]
protected 'parameters' =>
array (size=13)
'_token' => string 'DuNeITGaDF9K7eEMmU4HwX7nVLJUYDaZ1iYGT4dw' (length=40)
'fname' => string 'Joe' (length=3)
'lname' => string 'Peski' (length=5)
'gender' => string 'male' (length=4)
'msisdn' => string '254722000001' (length=12)
'email' => string 'joetry#hotmail.com' (length=18)
'residence' => string 'New Place' (length=9)
'age' => string 'teen' (length=4)
'bna' => string 'no' (length=2)
'mstatus' => string 'single' (length=6)
'kids' => string '4' (length=1)
'profession' => string 'IT' (length=2)
'submit' => string 'Submit' (length=6)

I believe it's working as intended. If you are not repopulating the fields with the old values then it looks like the page just gets redirected. Also you need to display the validation messages on the page.
https://laravel.com/docs/8.x/validation#repopulating-forms
https://laravel.com/docs/8.x/validation#quick-displaying-the-validation-errors

Validator doesn't read your status. Make sure you have a default value for this field.
If status is not required, you can change required to nullable, then create a default value after validation.
You need to display an error message to know what the error is.
$errors = $validator->errors();
Usually, this case occurs when you use a select box, check box, or something that can't read a value or empty, null.
The solution is to add a default value or add a hidden field with a default value.
<input type="hidden" name="status" value="0">
<select name="status">
...
</select>

Related

How to add id if there's custom validation rule when updating the record in Laravel?

How to add id in stud_num just like in email and username? the codes found in User Controller.
public function update(Request $request, $id)
{
$this->validate($request, [
'first_name' => 'required|max:255|regex:/^([^0-9]*)$/',
'middle_name' => 'nullable|max:255|regex:/^([^0-9]*)$/',
'last_name' => 'required|max:255|regex:/^([^0-9]*)$/',
'contact' => ['required', 'regex:/^(09|\+639)\d{9}$/'],
'course' => 'required',
'role_as' => 'required',
'stud_num' => ['required', 'unique:users,stud_num', 'max:15', new StrMustContain('TG')],
'username' => 'required|alpha_dash|unique:users,username,' . $id,
'email' => 'required|email:rfc,dns|unique:users,email,' . $id
]);
// codes for update
}
Just add id like email and username.
'stud_num' => ['required', 'unique:users,stud_num,'.$id, 'max:15', new StrMustContain('TG')]
you can write it like this:
'stud_num'=>['required',Rule::unique('users','stud_num')->ignore($id),'max:15',new StrMustContain('TG')]

Class "App\Http\Controllers\Survey" not found

Good day. My group our currently working in our final project using Laravel. I have this problem that I encounter.
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use app\database\seeders\Survey;
class SurveySeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$survey = Survey::create(['name' => 'Register Form', 'settings' => ['accept-guest-entries' => true]]);
$survey->questions()->create([
'content' => 'First Name',
]);
$survey->questions()->create([
'content' => 'Last Name',
]);
$survey->questions()->create([
'content' => 'Date of Birth (MM/DD/YYYY)',
]);
$survey->questions()->create([
'content' => 'Full Address',
]);
$survey->questions()->create([
'content' => 'Blood Group',
'type' => 'radio',
'options' => ['A', 'B', 'O', 'AB']
]);
$survey->questions()->create([
'content' => 'Phone Number',
'type' => 'number',
'rules' => ['numeric', 'min:11', 'max:11']
]);
}
}
I found some solutions but it doesn't work for me. I hope you can help me to get through this.
Where is your model Survey.php?
If in app/Models then you need to
use App\Models\Survey;

laravel validate unique fields on update

I am using the L5 repository and it has the validator package (https://github.com/andersao/laravel-validator) but I am have problems to do the validation of the unique fields on update it, anyone to help me???
******the example bellow I tried in this way on RULE_UPDATE but no success..
((((((FIELDS I WANT TO VALIDATE : people_id, email BECAUSE THESE ARE UNIQUE ONLY FOR REST OF THE USERS, NOT TO THIS CURRENT USER THAT ITS UPDATING )))))))
calling the validation in the UserService.php:
use Prettus\Validator\Contracts\ValidatorInterface;
public __construct(){
$this->validator = \App::make('App\Validators\UserValidator');
}
save($data){
if(!empty($data['id'])){
$this->validator->with($data)->passesOrFail(ValidatorInterface::RULE_UPDATE);
}else{
$this->validator->with($data)->passesOrFail(ValidatorInterface::RULE_CREATE);
}
}
namespace App\Validators;
use \Prettus\Validator\Contracts\ValidatorInterface;
use \Prettus\Validator\LaravelValidator;
class UserValidator extends LaravelValidator
{
protected $rules = [
ValidatorInterface::RULE_CREATE => [
'people_id' => 'required|unique:users',
'active' => 'required',
'available_chat' => 'required',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
'masters_id' => 'required',
],
ValidatorInterface::RULE_UPDATE => [
'id' => 'required',
'people_id' => 'required|unique:users,id,:id',
'active' => 'required',
'available_chat' => 'required',
'email' => 'required|string|email|max:255|unique:users,id,:id',
//'password' => 'required|string|min:6|confirmed',
//'masters_id' => 'required',
],
];
protected $messages = [
'id.required' => 'Usuário não encontrado!',
'people_id.required' => 'Pessoa é obrigatório',
'people_id.unique' => 'Pessoa já cadastrada',
'active.required' => 'Obrigatório',
'available_chat.required' => 'Obrigatório',
'email.required' => 'Digite o e-mail',
'password.required' => 'Digite a senha',
'password.min' => 'Digite uma senha com 6 caracteres',
'password.confirmed' => 'Confirme a senha corretamente',
'email.unique' => 'E-mail já cadastrado',
];
}
Try to put the id of the register in method setId
$this->validator->with($data)->setId($id)->passesOrFail(ValidatorInterface::RULE_UPDATE);
While updating you need to force a unique rule to Ignore Given ID
'people_id' => 'required|user,people_id,'.$id
//id is the primary id of the field which you want to update
with unique validation which must be ignored
https://laravel.com/docs/5.2/validation#rule-unique
Try to use the below changes it will work.
Add below code in your Validator for check Unique Email validation
ValidatorInterface::RULE_UPDATE => [
'email' => 'required|unique:customers,email,id'
],
After that set id for validation code like this
$this->validator->with($request->all())->setId($id)->passesOrFail(ValidatorInterface::RULE_UPDATE);

updated table and related table in Laravel

In Laravel I have relation:
class Address extends Model
{
protected $fillable = [
'street', 'city', 'post_code', 'country', 'state',
];
public function companies() {
return $this->hasMany('App\Company');
}
}
class Company extends Model
{
protected $fillable = [
'name', 'nip', 'email', 'phone', 'address_id'
];
public function address() {
return $this->belongsTo('App\Address');
}
}
and in CompaniesController.php I want to do update tables. My code looks like this:
public function update(Request $request, $id)
{
Company::where('id', $id)->update([
'name' => $request->name,
'email' => $request->email,
'phone' => $request->phone,
'nip' => $request->nip,
]);
}
How to also update the address associated with this company?
If the ID is your primary key, you should use find instead of where, as the former will guarantee that you only retrieve one row.
You can then query the relationship of your Company model, using the following code:
$company = Company::find($id);
$company->update([
'name' => $request->name,
'email' => $request->email,
'phone' => $request->phone,
'nip' => $request->nip,
]);
$company->address()->update([
'street' => 'street value',
'city' => 'city value',
'post_code' => 'post_code value',
'country' => 'country value',
'state' => 'state value',
]);
Please refer to the laravel docs

Validate whether multiple fields are unique simultaneously in laravel 5

This my request class rules.
return [
'title' => 'required|unique:event_cals,title',
'eventDate' => 'required|date|after:yesterday',
'venue' => 'required',
'time' => 'required',
'type' => 'required',
'unique:event_cals,eventDate,NULL,id,venue,$request->venue,time,$request->time'
];
I want to validate a rule like below.
'eventDate' && 'venue' && 'time' => 'unique'
There I need to check if there any row without same eventDate, venue and time altogether. Anyone knows how to declare such a rule?
This is the snapshot of db table.
Here is the possible solution:
<?php
return [
'title' => 'required|unique:event_cals,title',
'eventDate' => 'required|date|after:yesterday',
'venue' => 'required',
'time' => 'required',
'type' => 'required',
'event_date' => "unique:event_cals,event_date,NULL,id,venue,{$request->venue},time,{$request->time}",
];
I again want to highlight that; if you want that validator to work, you should make sure that the event_date and time should be correctly formatted.
An example unique check with additional wheres from our running project's update requests:
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
$id = $this->route('money');
return $rules = [
'name' => "required|string|min:3|max:255|unique:moneys,name,{$id},id,deleted_at,NULL,access,public",
];
}

Resources