Validation fails even if it has values Maatwebsite Laravel Validation - laravel

I'm currently using Maatwebsite collection when processing the import CSV file and validating it as well since I'm having hard time using the ToModel way. Here's how I validate the csv fields:
class ImportRooms implements ToCollection, WithStartRow
{
public function collection(Collection $rows)
{
foreach($rows as $row){
\Validator::make($row->toArray(), [
'name' => $row[0],
'room_code' => $row[1],
'user_name' => $row[2],
'email' => $row[3],
'password' => $row[4],
'remarks' => $row[5],
'name' => ['required', 'max:50'],
'room_code' => ['required', 'max:50'],
'user_name' => ['required', 'max:255'],
'email' => ['required', 'email', 'max:255','nullable'],
'password' => ['min:8','max:255','nullable'],
'remarks' => ['max:500'],
])->validate();
}
}
/**
* #return int
*/
public function startRow(): int
{
return 2;
}
}
This is a sample data I have.
Illuminate\Support\Collection {#565 ▼
#items: array:6 [▼
0 => "Room name"
1 => "Room101"
2 => "user"
3 => "fmacejkovic#example.org"
4 => "password"
5 => "remarks"
]
}
My problem now is that even though the values are all correct and valid, it still fails in the validation. I'm trying to assign to a specific variable so that when it fails, it'll return the row name instead of row number. Even though I use the row number, it still fails.

You have used incorrect syntax for Validator::make(), use this :
class ImportRooms implements ToCollection, WithStartRow
{
public function collection(Collection $rows)
{
foreach($rows as $row){
$row = $row->toArray();
$data = [
'name' => $row[0],
'room_code' => $row[1],
'user_name' => $row[2],
'email' => $row[3],
'password' => $row[4],
'remarks' => $row[5],
];
\Validator::make($data, [
'name' => ['required', 'max:50'],
'room_code' => ['required', 'max:50'],
'user_name' => ['required', 'max:255'],
'email' => ['required', 'email', 'max:255','nullable'],
'password' => ['min:8','max:255','nullable'],
'remarks' => ['max:500'],
])->validate();
}
}
/**
* #return int
*/
public function startRow(): int
{
return 2;
}
}

Refer https://laravel.com/docs/5.8/validation#automatic-redirection
//Convert row data into array and store it in a variable.
$row = $row->toArray();
//Set data to be validated.
$data = [
'name' => $row[0],
'room_code' => $row[1],
'user_name' => $row[2],
'email' => $row[3],
'password' => $row[4],
'remarks' => $row[5]
];
//Set conditions for validation.
$conditions = [
'name' => 'required|max:50',
'room_code' => 'required|max:50',
'user_name' => 'required|max:255',
'email' => 'required|email|max:255|nullable',
'password' => 'min:8|max:255|nullable',
'remarks' => 'max:500'
];
//Validate the excel data.
\Validator::make($data, $conditions)->validate();

Related

when i update two entities in postman i have null in laravel api

**when i update two entities in postman i have null in laravel api and
I have two entities one is for employees and the other is for personalDetails
this is my model employee:
class Employee extends Model implements HasMedia
{
use HasFactory, InteractsWithMedia;
protected $guarded = [];
protected $casts = [
];
public function personalDetails()
{
return $this->hasOne(PersonalDetails::class,'employee_id');
}
and this is the personalDetails model
class PersonalDetails extends Model implements HasMedia
{
use HasFactory, InteractsWithMedia;
protected $guarded = [];
protected $casts = [
'Date_of_birth' => 'date',
'joining_Date' => 'date',
];
public function employee()
{
return $this->belongsTo(Employee::class,'employee_id');
}
the controller is :
public function update(UpdateEmployeeRequest $request,Employee $employee)
{
$employee->update($request->validated());
return new EmployeeResource($employee);
the rout:
Route::middleware('auth:sanctum')->post('employee', [EmployeeController::class, 'store']);
and the UpdateEmployeeRequest is :
class UpdateEmployeeRequest extends FormRequest
{
public function rules()
{
return [
'Name_kanji' => ['required'],
'Name_katakana' => ['required'],
'Name_family_kanji' => ['required'],
'Name_family_katakana' => ['required'],
'employee_number' => ['required','numeric'],
'image' => ['required'],
'Employee_state' => ['required', Rule::in([EmployeeState::Employed, EmployeeState::OnLeave, EmployeeState::Resigned])],
'Employee_type' => ['required', Rule::in([EmployeeType::FullTime, EmployeeType::PartTime, EmployeeType::Director])],
'Department' => ['required', Rule::in([Department::Design, Department::Management, Department::Sales])],
'gender' => ['required', Rule::in([gender::male, gender::female])],
'Current_age' => ['required'],
'Company_day_based_age' => ['required'],
'jop_title' => ['required'],
'Daily_travel_expenses' => ['required'],
'office' => ['required'],
'Years_of_service' => ['required'],
'Email_address' => ['required'],
'My_number' => ['required','numeric'],
'address_id' => ['required'],
'domicile' => ['required'],
'Contact_number' => ['required'],
'Emergency_contact' => ['required'],
'Emergency_contact_relation' => ['required'],
'Need_work_Instruction' => ['required'],
'Date_of_birth*' => ['required|array'],
'Date_of_birth.*day' => ['required'],
'Date_of_birth.*year' => ['required'],
'Date_of_birth.*month' => ['required'],
'joining_Date*' => ['required|array'],
'joining_Date.*day' => ['required'],
'joining_Date.*year' => ['required'],
'joining_Date.*month' => ['required'],
];
}
public function validated($key = null, $default = null)
{
return [
'Name_kanji' => $this->Name_kanji,
'Name_katakana' => $this->Name_katakana,
'Name_family_katakana' => $this->Name_family_katakana,
'Name_family_kanji' => $this->Name_family_kanji,
'employee_number' => $this->employee_number,
'image' => $this->image,
'Employee_state' => $this->Employee_state,
'Employee_type' => $this->Employee_type,
'Department' => $this->Department,
'gender' => $this->gender,
'Current_age' => $this->Current_age,
'Company_day_based_age' => $this->Company_day_based_age,
'jop_title' => $this->jop_title,
'Daily_travel_expenses' => $this->Daily_travel_expenses,
'office' => $this->office,
'Years_of_service' => $this->Years_of_service,
'Email_address' => $this->Email_address,
'My_number' => $this->My_number,
'address_id' => $this->address_id,
'domicile' => $this->domicile,
'Contact_number' => $this->Contact_number,
'Emergency_contact' => $this->Emergency_contact,
'Emergency_contact_relation' => $this->Emergency_contact_relation,
'Need_work_Instruction' => $this->Need_work_Instruction,
'Date_of_birth' => Carbon::create(
$this->Date_of_birth['year'],
$this->Date_of_birth['month'],
$this->Date_of_birth['day'])->format('Y-m-d'),
'joining_Date' => Carbon::create(
$this->joining_Date['year'],
$this->joining_Date['month'],
$this->joining_Date['day'])->format('Y-m-d'),
];
}
}
and the EmployeeResource:
class EmployeeResource extends JsonResource
{
public function toArray($request)
{
return
[ 'id' => $this->id,
'Name_kanji' => $this->Name_kanji,
'Name_katakana' => $this->Name_katakana,
'Name_family_kanji' => $this->Name_family_kanji,
'Name_family_katakana' => $this->Name_family_katakana,
'employee_number' => $this->employee_number,
'image' => $this->personalDetails?->getFirstMediaUrl('PersonalDetails'),
'Employee_state' => $this->personalDetails?->Employee_state,
'My_number' => $this->personalDetails?->My_number,
'Employee_type' => $this->personalDetails?->Employee_type,
'Daily_travel_expenses' => $this->personalDetails?->Daily_travel_expenses,
'Current_age' => $this->personalDetails?->Current_age,
'Company_day_based_age' => $this->personalDetails?->Company_day_based_age,
'department' => $this->personalDetails?->department,
'office' => $this->personalDetails?->office,
'Gender' => $this->personalDetails?->Gender,
'Date_of_birth' =>[
'month' => $this->personalDetails?->Date_of_birth->month,
'day' => $this->personalDetails?->Date_of_birth->day,
'year' => $this->personalDetails?->Date_of_birth->year,
],
'joining_Date' =>[
'month' => $this->personalDetails?->joining_Date->month,
'day' => $this->personalDetails?->joining_Date->day,
'year' => $this->personalDetails?->joining_Date->year,
],
'Years_of_service' => $this->personalDetails?->Years_of_service,
'Email_address' => $this->personalDetails?->Email_address,
'address_id' => $this->personalDetails?->address_id,
'jop_title' => $this->personalDetails?->jop_title,
'domicile' => $this->personalDetails?->domicile,
'Contact_number' => $this->personalDetails?->Contact_number,
'Emergency_contact' => $this->personalDetails?->Emergency_contact,
'Emergency_contact_relation' => $this->personalDetails?->Emergency_contact_relation,
'Need_work_Instruction' => $this->personalDetails?->Need_work_Instruction,
and When I run the code in postman it shows empty values ​​and it doesn't store what's the problem with that
You have no route parameter named employee. When you type-hint a variable on your route action (Controller method signature in this case) you are getting Dependency injection, not Implicit Route Model Binding; there is no parameter to bind. You are getting an empty Employee model instance. This instance has no attributes so you are getting nulls for all the attributes you are trying to access.
The call to update is instantly just returning since the Model instance is non-existing.
What you have is the functional equivalent of this:
return new EmployeeResource(new Employee());
You would have to have a route parameter defined on your route and be passing some identifier for this parameter in the URL you are sending the request to:
Route::post('employee/{employee}', ...);
http://yoursite.com/employee/1

How to create custom validation rule that only accepts specific numbers in Laravel?

How to set custom validation rule that accept only 1.00, 1.25, 1.50, 1.75, 2.00, 2.25, 2.50, 2.75 and 3.00 in input text? The grades and grades1 are my inputs.
1.35 should be invalid (incase you're thinking the solution of divisible by 5)
1.26 should be invalid
FormRequest
public function rules()
{
return [
'user_id' => 'required',
'app_id' => 'nullable',
'subjects.*' => 'required|string',
'subjects1.*' => 'required|string',
'school_year' => 'required',
'grades.*' => ['required','numeric','lt:2.50'],
'grades1.*' => 'required|lt:2.50',
'units.*' => 'required|integer|min:1',
'units1.*' => 'required|integer|min:1',
'term' => 'required',
'term1' => 'required',
'total.*' => 'nullable',
'total1.*' => 'nullable',
'gwa_1st' => 'required|lte:1.75',
'gwa_2nd' => 'required|lte:1.75',
'year_level' => 'required|string',
'image' => 'required|mimes:jpeg,png,jpg',
'award_applied' => 'required|string',
'course_id' => 'required|string'
];
}
Controller
public function store(AchieversAwardRequest $request)
{
$data = $request->validated();
$award = new StudentApplicants();
$award->user_id = $data['user_id'];
$award->school_year = $data['school_year'];
$award->gwa_1st = $data['gwa_1st'];
$award->gwa_2nd = $data['gwa_2nd'];
$award->year_level = $data['year_level'];
if ($request->hasfile('image')) {
$file = $request->file('image');
$filename = time() . '.' . $file->getClientOriginalExtension();
$file->move('uploads/', $filename);
$award->image = $filename;
}
$award->award_applied = $data['award_applied'];
$award->course_id = $data['course_id'];
$award->save();
$lastid = $award->id;
}
One possible solution would be to use the in validation rule, something like the following:
$acceptable = [1.00, 1.25, 1.5, 2.75, 3.00];
$validator = Validator::make(['numbers_field' => 2.75], [
'numbers_field' => [Rule::in($acceptable)]
]);
Update
Add the rule to your AchieversAwardRequest custom FormRequest rules() method along with all your other rules:
public function rules()
{
return [
'user_id' => 'required',
'app_id' => 'nullable',
'subjects.*' => 'required|string',
'subjects1.*' => 'required|string',
'school_year' => 'required',
'grades.*' => ['required','numeric','lt:2.50'],
'grades1.*' => 'required|lt:2.50',
'units.*' => 'required|integer|min:1',
'units1.*' => 'required|integer|min:1',
'term' => 'required',
'term1' => 'required',
'total.*' => 'nullable',
'total1.*' => 'nullable',
'gwa_1st' => 'required|lte:1.75',
'gwa_2nd' => 'required|lte:1.75',
'year_level' => 'required|string',
'image' => 'required|mimes:jpeg,png,jpg',
'award_applied' => 'required|string',
'course_id' => 'required|string'
'field_name' => [Rule::in([1.00, 1.25, 1.5, 2.75, 3.00])]
];
}
Obviously, replace field_name with the name of your input field. You will also need to include use Illuminate\Validation\Rule; at the top of your AchieversAwardRequest.

Laravel Call to a member function validate() on null

I'm getting this error on Laravel Auth register
Call to a member function validate() on null
The error only happens when the validation passes, when it fails it shows returns to the register view with the correct errors.
I tried to dd after the if fails but it doesn't reach it:
protected function validator(array $data){
$req = new Request($data);
//dd($req,$data);
$this->validate($req,
[
'name' => ['required', 'string', 'max:50','min:3'],
'email' => ['required','email', 'unique:users'],
'password' => ['required', 'min:8', 'confirmed'],
'uni' => ['required'],
'city' => ['required'],
],[
'required' => 'هذا الحقل مطلوب',
'email'=>'نمط البريد الالكتروني غير صحيح',
'min'=>'يجب إدخال 8 حروف عالأقل',
'email.unique' => 'هذا البريد الالكتروني مستخدم',
'confirmed'=>'الرجاء التأكد من كلمة المرور',
'max'=>'50 حرف هو أقصى حد يمكن إدخاله',
'name.min'=>'الاسم قصير جدا',
]);
}
protected function create(array $data){
if ($this->validator($data)->fails()) {
return Redirect::back()->withErrors($this->validator($data))
->withInput();
}
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'photo'=>'img/user.jfif',
'university'=>$data['uni'],
'city'=>$data['city'],
]);
}
full code of RegisterController
https://pastebin.com/B8XcNbBR
and RegistersUsers (where the stack trace shows the error)
https://pastebin.com/BBTTStLL
Try this one
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:50','min:3'],
'email' => ['required','email', 'unique:users'],
'password' => ['required', 'min:8', 'confirmed'],
'uni' => ['required'],
'city' => ['required'],
],[
'required' => 'هذا الحقل مطلوب',
'email'=>'نمط البريد الالكتروني غير صحيح',
'min'=>'يجب إدخال 8 حروف عالأقل',
'email.unique' => 'هذا البريد الالكتروني مستخدم',
'confirmed'=>'الرجاء التأكد من كلمة المرور',
'max'=>'50 حرف هو أقصى حد يمكن إدخاله',
'name.min'=>'الاسم قصير جدا',
]);
}
protected function create(array $data){
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'photo'=>'img/user.jfif',
'university'=>$data['uni'],
'city'=>$data['city'],
]);
}

How can I redirect to function controller after registration in laravel 8

I hope you can help me, I wanna customize the registercontroller from Laravel, I have this, but after the user is registered send me a JSON of data, how can I do for don't send me the JSON and redirect to the HomeController.
Thanks.
PD. Sorry for my English.
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => ['required', 'string', 'max:255'],
'nombre' => ['required', 'string', 'max:255','unique:users'],
'telefono' => ['required', 'numeric', 'max:99999999', 'min:00000000'],
'direccion' => ['required', 'string', 'max:255'],
'sueldo' => ['numeric','min:0.01','max:0.99'],
//'foto' => ['string', 'max:255'],
'email' => ['string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:4', 'confirmed'],
]);
if ($request->hasFile('foto')) {
$request = request();
$file = $request->file('foto');
$nom_imagen = time().".".$file->getClientOriginalExtension();
$upload_path = 'imagenes/';
$profile_image_url = $upload_path . $nom_imagen;
$success = $file->move($upload_path, $nom_imagen);
} else {
$nom_imagen = '';
}
return User::create([
'name' => $request->input('name'),
'nombre' => $request->input('nombre'),
'telefono' => $request->input('telefono'),
'direccion' => $request->input('direccion'),
'sueldo' => $request->input('sueldo'),
'email' => $request->input('email'),
'foto' => $nom_imagen,
'password' => Hash::make($request['password']),
return redirect()->action('HomeController#index'),
]);
}
Laravel 5.5: Execute a method before registration
HomeController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
return view('index');
}
}
You are returning the return value of User::create() which will be a User object which gets converted to json when returned as a response.
Also since your HomeController is protected by 'auth' middleware you need to login the user before redirecting to '/home'
use Illuminate\Support\Facades\Auth;
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => ['required', 'string', 'max:255'],
'nombre' => ['required', 'string', 'max:255','unique:users'],
'telefono' => ['required', 'numeric', 'max:99999999', 'min:00000000'],
'direccion' => ['required', 'string', 'max:255'],
'sueldo' => ['numeric','min:0.01','max:0.99'],
//'foto' => ['string', 'max:255'],
'email' => ['string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:4', 'confirmed'],
]);
if ($request->hasFile('foto')) {
$request = request();
$file = $request->file('foto');
$nom_imagen = time().".".$file->getClientOriginalExtension();
$upload_path = 'imagenes/';
$profile_image_url = $upload_path . $nom_imagen;
$success = $file->move($upload_path, $nom_imagen);
} else {
$nom_imagen = '';
}
$user = User::create([
'name' => $request->input('name'),
'nombre' => $request->input('nombre'),
'telefono' => $request->input('telefono'),
'direccion' => $request->input('direccion'),
'sueldo' => $request->input('sueldo'),
'email' => $request->input('email'),
'foto' => $nom_imagen,
'password' => Hash::make($request['password']),
]);
Auth::guard()->login($user);
return redirect('/home');
}
Move the redirect after create user , try like this
User::create([
'name' => $request->input('name'),
'nombre' =>$request->input('nombre'),
'telefono' => $request->input('telefono'),
'direccion' => $request->input('direccion'),
'sueldo' => $request->input('sueldo'),
'email' => $request->input('email'),
'foto' => $nom_imagen,
'password' => Hash::make($request['password'])
]);
return redirect()->action('HomeController#index'),

How to check if in inside validtion request?

I have this validation request:
public function rules()
{
return [
'user_id' => ['required', 'exists:users,id'],
'address_type' => ['required', 'in:main_address,new_address'],
'governorate_id' => ['required', 'exists:governorates,id'],
'area_id' => ['required', 'exists:areas,id'],
'phone' => ['required', 'string', 'max:15'],
'nearly_area' => ['required', 'string', 'max:200'],
];
}
How can check if the user choose in address_type (main_address one) ignore the rest of fields and if new_address the rest fields should be required ??
Use required_if like:
public function rules()
{
return [
'user_id' => ['required', 'exists:users,id'],
'address_type' => ['required', 'in:main_address,new_address'],
'governorate_id' => ['required_if:address_type,==,new_address', 'exists:governorates,id'],
'area_id' => ['required_if:address_type,==,new_address', 'exists:areas,id'],
'phone' => ['required_if:address_type,==,new_address', 'string', 'max:15'],
'nearly_area' => ['required_if:address_type,==,new_address', 'string', 'max:200'],
];
}

Resources