I'm Importing a CSV file to a livewire component and trying to run some validation for each row of the file but I'm having problems doing this. It seems that my validation is doing nothing.
Here is how my Livewire component looks like:
namespace App\Http\Livewire\Modals;
use Validator;
use Livewire\Component;
use App\Http\Traits\Csv;
use App\Models\AccountUser;
use Livewire\WithFileUploads;
use Illuminate\Support\Facades\Auth;
class ImportExtensions extends Component
{
use WithFileUploads;
public $clientID;
public $showModal = false;
public $upload;
public $columns;
public $fieldColumnMap = [
'first_name' => '',
'last_name' => '',
'email' => '',
'password' => '',
'extension' => '',
'user_type' => '',
];
protected $rules = [
'fieldColumnMap.first_name' => 'required|max:255',
'fieldColumnMap.last_name' => 'required|max:255',
'fieldColumnMap.email' => 'required|max:255',
'fieldColumnMap.password' => 'required|max:255',
'fieldColumnMap.extension' => 'required|max:255',
'fieldColumnMap.user_type' => 'required|max:255',
];
protected $validationAttributes = [
'fieldColumnMap.first_name' => 'First Name',
'fieldColumnMap.last_name' => 'Last Name',
'fieldColumnMap.email' => 'Email',
'fieldColumnMap.password' => 'Password',
'fieldColumnMap.extension' => 'Extension',
'fieldColumnMap.user_type' => 'User Type',
];
public function updatingUpload($value)
{
Validator::make(
['upload' => $value],
['upload' => 'required|mimes:txt,csv'],
)->validate();
}
public function updatedUpload()
{
$this->columns = Csv::from($this->upload)->columns();
$this->guessWhichColumnsMapToWhichFields();
}
public function import()
{
// Validate that you are importing any data
$this->validate();
$importCount = 0;
Csv::from($this->upload)
->eachRow( function ($row) use (&$importCount){
$eachRow = $this->extractFieldsFromRow($row);
//Validate the data of each Row to make to make sure you don't import duplicate records
$this->validateOnly(collect($eachRow), [
'fieldColumnMap.first_name' => 'required|max:255',
'fieldColumnMap.last_name' => 'required|max:255',
'fieldColumnMap.email' => 'required|max:255|email|unique:account_users, email',
'fieldColumnMap.extension' => 'required|numeric|unique:account_users, extension',
'fieldColumnMap.password' => 'required|max:255',
'fieldColumnMap.user_type' => 'required|in:user,admin',
]);
//If validation fails, it should skip the create extension part and run the next row
//If validation pass, then create the Extension
AccountUser::create([
'user_id' => Auth::user()->id,
'account_id' => $this->clientID,
'first_name' => $eachRow['first_name'],
'last_name' => $eachRow['last_name'],
'email' => $eachRow['email'],
'password' => $eachRow['password'],
'extension' => $eachRow['extension'],
'user_type' => $eachRow['user_type'],
]);
$importCount++;
});
$this->reset();
$this->emit('refreshExtensions');
$this->notify('Successfully Imported '.$importCount.' Extensions');
}
Also, how can I make so that if the validation fails it goes to the next row instead of trying to create the extension.
Thanks.
I was able to create custom rules for just this. if one row fails validation, I just throw an error. So, basically either all rows pass or all fails.
Here is how it looks like now:
public function import()
{
// Validate that you are importing any data
$this->validate();
$importCount = 0;
Csv::from($this->upload)
->eachRow( function ($row) use (&$importCount){
$eachRow = $this->extractFieldsFromRow($row);
$validatedData = Validator::make([
'first_name' => $eachRow['first_name'],
'last_name' => $eachRow['last_name'],
'email' => $eachRow['email'],
'password' => $eachRow['password'],
'extension' => $eachRow['extension'],
'user_type' => $eachRow['user_type'],
],[
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email|unique:account_users',
'extension' => 'required|numeric|unique:account_users',
'password' => 'required|max:255',
'user_type' => 'required|in:user,admin',
],);
if($validatedData->fails()){
$this->notify(['error','Oops something went wrong!']);
}else{
AccountUser::create([
'user_id' => Auth::user()->id,
'account_id' => $this->clientID,
'first_name' => $eachRow['first_name'],
'last_name' => $eachRow['last_name'],
'email' => $eachRow['email'],
'password' => $eachRow['password'],
'extension' => $eachRow['extension'],
'user_type' => $eachRow['user_type'],
]);
$importCount++;
}
});
$this->reset();
$this->emit('refreshExtensions');
if($importCount!=0) $this->notify(['success','Successfully Imported '.$importCount.' Extensions']);
}
Related
I'm using this code for User Sign Up in Laravel:
class UsersController extends Controller
{
public function register(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:8',
'phone' => 'required|unique:users',
'type' => 'boolean',
'verified' => 'boolean'
]);
$user = User::create([
'name' => $validatedData['name'],
'email' => $validatedData['email'],
'phone' => $validatedData['phone'],
'type' => $validatedData['type'],
'verified' => $validatedData['verified'],
'password' => Hash::make($validatedData['password']),
]);
$token = $user->createToken('auth_token')->accessToken;
return response()->json([
'user' => $user,
'access_token' => $token,
'token_type' => 'Bearer',
]);
}
As you can see , some of my field are unique , so I want to display a message in my front side that displays the error from the back side.
Exemple : When a user enters a used phone number , I want to return an error saying : this phone number has been used .
How can I achieve this ? Thank you.
You can get a User record from the database by phone. If the record exists, then do your logic
class UsersController extends Controller
{
public function register(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:8',
'phone' => 'required|unique:users',
'type' => 'boolean',
'verified' => 'boolean'
]);
// get a user record by phone
$record = User::where('phone', $validatedData['phone'])->find();
if (!empty($record)) {
return response()->json([
'error' => 'this phone number has been used'
])
}
//.....
}
I'm making an app that runs like google form using Laravel 5.7. Here is the form table that i already made:
I made an eloquent model so that each Name in Personal details table has one record that contains all these table and insert filled table into database after click submit button. The problem is, it didn't successfully inserted into database. I don't know what's the problem, here are my codes:
PersonalDetails.php (eloquent model)
namespace App;
use Illuminate\Database\Eloquent\Model;
class PersonalDetails extends Model
{
protected $table = 'personal_details';
protected $guarded = ['id'];
public function accomodation()
{
return $this->hasOne('App\Accomodation');
}
public function course()
{
return $this->hasOne('App\Course');
}
public function proposedStudy()
{
return $this->hasOne('App\ProposedStudy');
}
public function emergencyContact()
{
return $this->hasOne('App\EmergencyContact');
}
public function englishTestResult()
{
return $this->hasOne('App\EnglishTestResult');
}
public function homeInstitution()
{
return $this->hasOne('App\HomeInstitution');
}
public function insurance()
{
return $this->hasOne('App\Insurance');
}
}
FormController.php
public function submit(Request $request) {
$request->validate([
// Personal Details
'fullname' => 'required|string',
'nationality' => 'required|string',
'date_of_birth' => 'required|string',
'passport_number' => 'required|string',
'issuing_country' => 'required|string',
'date_of_issue' => 'required|string',
'date_of_expiry' => 'required|string',
'blood_type' => 'required|string',
'marital_status' => 'required|string',
'address' => 'required|string',
'city' => 'required|string',
'postal_code' => 'required|numeric',
'province' => 'required|string',
'country' => 'required|string',
'phone' => 'required|string',
'mobile' => 'required|string',
'email' => 'required|email',
'address2' => 'nullable|text',
'city2' => 'nullable|string',
'postal_code2' => 'nullable|numeric',
'province2' => 'nullable|string',
'country2' => 'nullable|string',
'phone2' => 'nullable|string',
'contact_name' => 'required|string',
// Home Institution
'name' => 'required|string',
'address' => 'required|string',
'phone' => 'required|string',
'email' => 'required|email',
'website' => 'required|string',
'faculty_dep' => 'required|string',
'start_year' => 'required|string',
'gpa' => 'required|string',
// Proposed Study
'semester' => 'required|in:Semester I (Aug-Jan),Semester II (Feb-Jun)',
'academic_year' => 'required|string',
'faculty' => 'required|string',
'department' => 'required|string',
'study_period' => 'required|string',
'start_date' => 'required|string',
'end_date' => 'required|string',
// Course
'course_title' => 'required|string',
'credit' => 'required|string',
// English Test Result
'test' => 'required|string',
'score' => 'required|numeric',
'test_center' => 'required|string',
'date_tested' => 'required|string',
// Insurance
'insurance_name' => 'required|string',
'validity' => 'required|string',
'cover' => 'required|string',
// Accomodation
'accomodation_help' => 'required|in:YES,NO',
'adress' => 'required|string',
'contact_person' => 'required|string',
// Contact of Emergency
'fullname' => 'required|string',
'relationship' => 'required|string',
'address' => 'required|string',
'phone' => 'required|string',
'mobile' => 'required|string',
'email' => 'required|email',
]);
PersonalDetails::create([
'fullname' => $request->input('name'),
'nationality' => $request->input('nationality'),
'date_of_birth' => $request->input('dob'),
'passport_number' => $request->input('passport'),
'issuing_country' => $request->input('is_country'),
'date_of_issue' => $request->input('doi'),
'date_of_expiry' => $request->input('doe'),
'blood_type' => $request->input('blood'),
'marital_status' => $request->input('maritial'),
'address' => $request->input('address'),
'city' => $request->input('city'),
'postal_code' => $request->input('postal'),
'province' => $request->input('state'),
'country' => $request->input('country'),
'phone' => $request->input('phone'),
'mobile' => $request->input('mobile'),
'email' => $request->input('email'),
'address2' => $request->input('address2'),
'city2' => $request->input('city2'),
'postal_code2' => $request->input('postal2'),
'province2' => $request->input('state2'),
'country2' => $request->input('country2'),
'phone2' => $request->input('phone2'),
'contact_name' => $request->input('contact_name'),
]);
HomeInstitution::create([
'name' => $request->input('institution'),
'address' => $request->input('i_address'),
'phone' => $request->input('i_phone'),
'email' => $request->input('i_email'),
'website' => $request->input('web'),
'faculty_dep' => $request->input('faculty_dept'),
'start_year' => $request->input('s_year'),
'gpa' => $request->input('gpa'),
]);
ProposedStudy::create([
'semester' => $request->input('duration'),
'academic_year' => $request->input('f_year') . '/' . $request->input('l_year'),
'faculty' => $request->input('faculty'),
'department' => $request->input('department'),
'study_period' => $request->input('spesific_period'),
'start_date' => $request->input('start_date'),
'end_date' => $request->input('end_date'),
]);
Course::create([
'course_title' => $request->input('course_1'),
'credit' => $request->input('credit_1'),
]);
EnglishTestResult::create([
'test' => $request->input('toefl'),
'score' => $request->input('score_toefl'),
'test_center' => $request->input('place_toefl'),
'date_tested' => $request->input('date_toefl'),
]);
Insurance::create([
'insurance_name' => $request->input('insurance'),
'validity' => $request->input('valid_date'),
'cover' => $request->input('cover'),
]);
Accomodation::create([
'accomodation_help' => $request->input('opt_acc'),
'adress' => $request->input('adress_acc'),
'contact_person' => $request->input('cp_acc'),
]);
EmergencyContact::create([
'fullname' => $request->input('emergency_name'),
'relationship' => $request->input('relationship'),
'address' => $request->input('address_emergency'),
'phone' => $request->input('emergency_phone'),
'mobile' => $request->input('emergency_mobile'),
'email' => $request->input('emergency_email'),
]);
// return back()-> with('success', 'Berhasil submit!');
}
Finally after all these struggles to figured out the problem, i just realized that i put wrong name in validation rules. The name on the left side of validation rules is different with name in html so i reformed the name in html and validation rules.
The big deal is i didn't put any validation error message after submit so that it won't inserted into database. After i put some error message, all of the field returned error that says "The :attribute is required". Simply because the name in validation is different with the html name :D
Thank you guys for helped me to figured out the problem, i worked it out :))
try with model path,if model folder is inside App then App\model;
eg:-
App\Insurance::create([
'insurance_name' => $request->input('insurance'),
'validity' => $request->input('valid_date'),
'cover' => $request->input('cover'),
]);
add $fillalbe in Model:
protected $fillable=['full_name','nationality','...']
you will need to specify fillalbe attribute on the model. read more at https://laravel.com/docs/5.7/eloquent#mass-assignment
Can you check your table migration or model relation, then revision your form controller.
I am create example from your code and successfull insert into database.
Personal Details Migration
Schema::create('personal_details', function (Blueprint $table) {
$table->increments('id');
$table->string('fullname')->nullable();
$table->string('nationality')->nullable();
$table->timestamps();
});
Home Institution Migration
Schema::create('home_institution', function (Blueprint $table) {
$table->integer('personal_details_id')->unsigned()->primary();
$table->string('name')->nullable();
$table->string('address')->nullable();
$table->timestamps();
#Foreign to Table Personal Details.
$table->foreign('personal_details_id')->references('id')->on('personal_details')->onUpdate('cascade')
->onDelete('cascade');
});
Personal Detail Model Relation
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class PersonalDetails extends Model
{
protected $guarded = ['id'];
public function homeInstitution()
{
return $this->hasOne('App\HomeInstitution');
}
# Other your Relation
}
Form Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\PersonalDetails;
class FormController extends Controller
{
public function index()
{
return view('form.index');
}
public function submit(Request $request)
{
$request->validate([
// Personal Details
'fullname' => 'required|string',
'nationality' => 'required|string',
// Home Institution
'name' => 'required|string',
'address' => 'required|string',
]);
$pd = PersonalDetails::create(
['fullname' => $request->get('fullname'), 'nationality' => $request->get('nationality')]
);
# Insert into HomeInstitution => base on Model Relation from PersonalDetails
$pd->homeinstitution()->create(
['name' => $request->get('name'), 'address' => $request->get('address')]
);
# Insert into other youR relation
/*$pd->example()->create(
[]
);*/
return dd('Successfull Insert');
}
}
Maybe its can help you.
I need the filled field remains its input data. but this happened it's gone. What should I do to make it still remain? I used Laravel 5.4. already used this command " $req->flash(); " but still failed
Here is my output
and this is my code:
public function register_create(Request $req) {
$req->flash();
$req->validate([
'name' => 'required',
'matrix-number' => 'required',
'ic-number' => 'required',
'faculty' => 'required',
'programme' => 'required',
'part' => 'required',
'group' => 'required',
'email' => 'required',
'phone-number' => 'required'
]);
$name = Helpers::raw($req->input('name'));
$matrix_number = $req->input('matrix-number');
$ic_number = $req->input('ic-number');
$faculty = Helpers::raw($req->input('faculty'));
$programme = $req->input('programme');
$part = $req->input('part');
$group = $req->input('group');
$email = $req->input('email');
$phone_number = $req->input('phone-number');
User::create([
'name' => $name,
'matrix_number' => $matrix_number,
'ic_number' => $ic_number,
'faculty' => $faculty,
'programme' => $programme,
'part' => $part,
'group' => $group,
'email' => $email,
'phone_number' => $phone_number,
'password' => $ic_number
]);
{
if (session('validate')) {
$req -> validate;
return redirect()->action('HomeController#login');
}
else
{
$req->session()->reflash();
$req->session()->put('some_key', $req->all());
return redirect()->back()->withInput();
}
}
}
as the title says..
My project was hashing passwords properly until recently I noticed that passwords of new users dont get hashed while it is supposed to be as I am using Hash::make and I used Hash on the top of the controller. Please Help...
here is my User controller
I am using laravel 5.6 if this would help...
namespace App\Http\Controllers\Auth;
use App\User;
use Hash;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request;
class RegisterController extends Controller
{
use RegistersUsers;
protected $redirectPath = '/admin';
protected function validator(array $data)
{
return Validator::make($data, [
'f_name' => 'required|string|max:255',
'user_id' => 'required|string|max:255|unique:person',
'm_name' => 'required|string|max:255',
'g_name' => 'required|string|max:255',
's_name' => 'required|string|max:255',
'address' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:person',
'field_of_study'=> 'string|max:255',
'gender' => 'required|boolean',
'b_date' => 'required|date|max:255',
'type' => 'required|integer|max:3',
'job_title' => 'string|max:255',
'orgnaization' => 'required|string|max:255',
'sector' => 'boolean',
'mobile' => 'required|string|min:10',
'password' =>'required|string|min:10',
]);
}
protected function create(array $data)
{
return User::create([
'f_name' => $data['f_name'],
'user_id' => $data['user_id'],
'm_name' => $data['m_name'],
'g_name' => $data['g_name'],
's_name' => $data['s_name'],
'address' => $data['address'],
'field_of_study' => $data['field_of_study'],
'gender' => $data['gender'],
'b_date' => $data['b_date'],
'type' => $data['type'],
'job_title' => $data['job_title'],
'orgnaization' => $data['orgnaization'],
'mobile' => $data['mobile'],
'sector' => $data['sector'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
public function register(Request $request)
{
if($user=User::create($request->all()))
{
return redirect('Admin')->with('message', 'done');
}
else
{
return redirect()->back()->with('error', 'error');
}
}
}
and here is my model
protected $fillable = [
'f_name','m_name','g_name','s_name','address','user_id','field_of_study','gender','b_date','type','job_title','orgnaization','mobile','sector', 'email', 'password',
];
protected $hidden = [
'password',
];
use
if ($user = $this->create($request->all()))
instead of
if($user=User::create($request->all()))
You're not calling your controller function, you're just doing User::create. that's why none of your data is being hashed
Maybe this code help you:
$inputData = $request->all();
$inputData['password'] = bcrypt($request->password);
User::create($inputData);
I am working on a school project, and I have a registration form.
I am working in laravel 5 and am using the auth package of laravel.
I added my extra registration forms like this
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
'lastName' => 'required|string|max:55|',
'streetAdress' => 'required|string|max:255|',
'houseNumber' => 'required|integer|min:1|',
'city' => 'required|string|max:255|',
'postal_code' => 'required|string|max:255|',
'user_phone_number' => 'required|numeric|min:10|',
'birth_day' => 'required|date|min:1|',
'user_parent_name' => 'required|string|max:255|',
'user_parent_email' => 'required|email|max:255|',
'user_parent_phone' => 'required|numeric|min:10|',
]);
}
That is my validator here is my create
protected function create(array $data)
{
$birthday = explode('-', $data['birth_day']);
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'lastName' => $data['lastName'],
'streetAdress' => $data['streetAdress'],
'houseNumber' => $data['houseNumber'],
'city' => $data['city'],
'user_phone_number' => $data['user_phone_number'],
'postal_code' => $data['postal_code'],
'birth_day_day' => $birthday[2],
'birth_day_month' => $birthday[1],
'birth_day_year' => $birthday[0],
'user_parent_name' => $data['user_parent_name'],
'user_parent_email' => $data['user_parent_email'],
'user_parent_phone' => $data['user_parent_phone'],
]);
}
Here is my html
<input id="user_phone_number" type="number" class="form-control" name="user_phone_number" value="{{ old('user_phone_number') }}" required>
In my database I have a column called user_phone_number. Everything else does store but the user_phone_number is still NULL
Thanks in advance
I was looking through my model and i found the problem. i didnt had the fillable option for user_phone_number,
protected $fillable = [
'name', 'email', 'password', 'lastName', 'streetAdress', 'houseNumber', 'city',
'postal_code', 'birth_day_year', 'user_phone_number', 'birth_day_month', 'birth_day_day', 'user_parent_name',
'user_parent_email', 'user_parent_phone',
];
Was missing user_phone_number
**if you are store phone no in database use this migration work for me
$table->bigInteger('phone');