I have a textarea where a user can bulk add clients. In the textarea they would add the clients like this
client 1,client1#domain.com,client username 1
client 2,client2#domain.com,client username 2
client 3,client3#domain.com,client username 3
Here is what I have so far
public function bulkClients()
{
$bulk = request('bulk_clients');
$split = explode("\n",$bulk);
foreach($split as $row)
{
$split_row = explode(",", $row);
$name = $split_row[0];
$email = $split_row[1];
$username = $split_row[2];
$validate = Validator::make($email, [
$email => 'email',
$username => 'unique:App\User,username'
]);
if($validate->fails())
{
$messages = $validate->messages();
return response()->json([
'messages' => $messages
]);
}
}
}
What I would like to know is how can I validate that $email is an email or that $username is unique.
The first param of Validator::make should be an array and the second is the rules for the keys of the array.
public function bulkClients()
{
$bulk = request('bulk_clients');
$split = explode("\n",$bulk);
foreach($split as $row)
{
$split_row = explode(",", $row);
$client['name'] = $split_row[0];
$client['email'] = $split_row[1];
$client['username'] = $split_row[2];
$validate = Validator::make($client, [
'email' => 'email',
'username' => 'unique:App\User,username'
]);
if($validate->fails())
{
$messages = $validate->messages();
return response()->json([
'messages' => $messages
]);
}
}
}
You find all available rules in the docs:
$validate = Validator::make([ 'email' => $split_row[1],
'username' => $split_row[2]
], [
'email' => 'string',
'username' => 'unique:App\User,username'
]);
However, for email, I would rather check if its a valid email instead of a string. Thus,
'email' => 'email'
would be recommended.
I would suggest using the validator for the whole array instead of validating it row by row:
$clients = Str::of(request()->get('bulk_clients'))
->explode("\n")
->map(fn ($value) => Str::of($value)->explode(','))
->toArray();
$validator = Validator::make(compact('clients'), [
'clients' => 'array',
'clients.*.0' => 'required|string',
'clients.*.1' => 'required|email',
'clients.*.2' => 'required|unique:App\User,username',
]);
Related
I have a big struggle about adding file uploading to an existing laravel 6 form.
I want to add the file url to database for future to be displayed (or downloaded).
When i try to do something nothing is happaning, nothing in DB nothing in file dir.
Here is my model:
protected $fillable = [
'age',
'last_rab',
'names',
'email',
'phone',
'last_pos',
'cv',
'msg',
'status'
];
Here is my Controller:
public function store(Request $request)
{
$request->validate([
'names' => 'required',
'age' => 'required',
'last_rab' => 'required',
'last_pos' => 'required',
'phone' => 'required',
'cv' => 'required|mimes:doc,docx,pdf,txt|max:2048',
'msg' => 'required'
]);
if ($request->captcha != 58) {
return redirect()->back()->withInput()->with('warning', 'Wrong');
}
$karieri = new Karieri;
$karieri->age = $request->age;
$karieri->last_rab = $request->last_rab;
$karieri->names = $request->names;
$karieri->email = $request->email;
$karieri->phone = $request->phone;
$karieri->last_pos = $request->last_pos;
if ($request->hasfile('cv')) {
$file = $request->file('cv');
$name = time().'.'.$file->extension();
$file->move(public_path() . '/storage/app/public', $name);
$data = $name;
$karieri->cv = json_encode($data);
}
$karieri->msg = $request->msg;
$karieri->status = 0;
$karieri->save();
return redirect()->back()->with('success', 'Thanks');
}
Can somebody say how to do this?
I have a submit and update function for my form and in that form, the user can choose to add an additional row of inputs. These inputs will be saved in a new row, basically, one user can have several rows in the database. I have a problem with the update function, where if the user originally has two rows answered, in the update function if they still fill in two rows, both of the rows in the database will be updated, however, only the first row is getting updated. I tried accessing the key for the arrays and updating based on the array keys but it doesn't work.
Here is my whole controller:
<?php
namespace App\Http\Livewire;
use Illuminate\Support\Facades\Validator;
use App\Http\Livewire\Field;
use Illuminate\Http\Request;
use App\Helpers\Constant;
use App\Models\User;
use App\Models\Application;
use App\Models\Model1;
use App\Models\Model2;
use App\Models\Model3;
use App\Models\Model4;
use Livewire\Component;
use DB;
class ModelComponent extends Component
{
public $i = 1;
public $updateMode = false;
public $model2Rows = [];
public $model4Rows = [];
public $showDiv1 = false;
public $showDiv2 = false;
public $showDiv3 = false;
public $showDiv4 = false;
public $m1_field;
public $m1_field2;
public $m2_field;
public $m2_field2;
public $m3_field;
public $m3_field2;
public $m4_field;
public $m4_field2;
public function openDiv($divNum)
{
if($divNum == 1) {
$this->showDiv1 =! $this->showDiv1;
} else if($divNum == 2) {
$this->showDiv2 =! $this->showDiv2;
} else if($divNum == 3) {
$this->showDiv3 =! $this->showDiv3;
} else if($divNum == 4) {
$this->showDiv4 =! $this->showDiv4;
}
}
public function addMoreModel2Rows($i)
{
$i = $i + 1;
$this->i = $i;
array_push($this->model2Rows , $i);
}
public function addMoreModel4Rows($i)
{
$i = $i + 1;
$this->i = $i;
array_push($this->model4Rows , $i);
}
public function removeModel2Rows($i)
{
unset($this->model2Rows[$i]);
}
public function removeModel4Rows($i)
{
unset($this->model4Rows[$i]);
}
public function submit()
{
$user = auth()->user();
$application = Application::create([
'app_type_id' => 1,
'approval_status_id' => 1
]);
$application->users()->save($user);
$rules = [];
$validatedData = [];
if($this->showDiv1){
$rules = array_merge($rules, [
'm1_field' => 'required',
'm1_field2' => 'required',
]);
}
if($this->showDiv2){
$rules = array_merge($rules, [
'm2_field.0' => 'required',
'm2_field2.0' => 'required',
'm2_field.*' => 'required',
'm2_field2.*' => 'required',
]);
}
if($this->showDiv3){
$rules = array_merge($rules, [
'm3_field' => 'required',
'm3_field2' => 'required',
]);
}
if($this->showDiv4){
$rules = array_merge($rules, [
'm4_field.0' => 'required',
'm4_field2.0' => 'required',
'm4_field.*' => 'required',
'm4_field2.*' => 'required',
]);
}
$validatedData = $this->validate($rules);
if($this->showDiv1){
Model1::create([
'user_id' => $user->user_id,
'm1_field' => $validatedData['m1_field'],
'm1_field2' => $validatedData['m1_field2'],
]);
}
if($this->showDiv2){
foreach ($this->m2_field as $key => $value){
Model2::create([
'user_id' => $user->user_id,
'm2_field' => $validatedData['m2_field'][$key],
'm2_field2' => sanitize_money($validatedData['m2_field2'][$key]),
]);
}
}
if($this->showDiv3){
Model3::create([
'user_id' => $user->user_id,
'm3_field' => $validatedData['m3_field'],
'm3_field2' => $validatedData['m3_field2'],
]);
}
if($this->showDiv4){
foreach ($this->m4_field as $key => $value){
Model4::create([
'user_id' => $user->user_id,
'm4_field' => $validatedData['m4_field'][$key],
'm4_field2' => sanitize_money($validatedData['m4_field2'][$key]),
]);
}
}
$user->save();
alert('success','Your details are saved.');
return redirect()->route('website.landing');
}
public function update()
{
// get user info in session
$user = auth()->user();
$i = 0;
$model2 = Model2::where('user_id', $user->user_id)->get();
$model4 = Model4::where('user_id', $user->user_id)->get();
$rules = [];
$validatedData = [];
if($this->showDiv1){
$rules = array_merge($rules, [
'm1_field' => 'required',
'm1_field2' => 'required',
]);
}
if($this->showDiv2){
$rules = array_merge($rules, [
'm2_field.0' => 'required',
'm2_field2.0' => 'required',
'm2_field.*' => 'required',
'm2_field2.*' => 'required',
]);
}
if($this->showDiv3){
$rules = array_merge($rules, [
'm3_field' => 'required',
'm3_field2' => 'required',
]);
}
if($this->showDiv4){
$rules = array_merge($rules, [
'm4_field.0' => 'required',
'm4_field2.0' => 'required',
'm4_field.*' => 'required',
'm4_field2.*' => 'required',
]);
}
$validatedData = $this->validate($rules);
if($this->showDiv1){
EmploymentDetail::updateOrCreate(
[
'user_id' => $user->user_id,
],
[
'm1_field' => $validatedData['m1_field'],
'm1_field2' => $validatedData['m1_field2'],
]);
}
if($this->showDiv2){
foreach ($this->m2_field as $key => $value){
$partTime[$key]->updateOrCreate(
[
'user_id' => $user->user_id,
],
[
'm2_field' => $validatedData['m2_field'][$key],
'm2_field2' => sanitize_money($validatedData['m2_field2'][$key]),
]);
}
}
if($this->showDiv3){
Model3::updateOrCreate(
[
'user_id' => $user->user_id,
],
[
'm3_field' => $validatedData['m3_field'],
'm3_field2' => $validatedData['m3_field2'],
]);
}
if($this->showDiv4){
foreach ($this->m4_field as $key => $value){
if(!empty($model4[$i])){
$model4[$i]->updateOrCreate(
[
'user_id' => $user->user_id,
],
[
'm4_field' => $validatedData['m4_field'][$key],
'm4_field2' => sanitize_money($validatedData['m4_field2'][$key]),
]);
} else {
Model4::create([
'user_id' => $user->user_id,
'm4_field' => $validatedData['m4_field'][$key],
'm4_field2' => sanitize_money($validatedData['m4_field2'][$key]),
]);
}
}
}
alert('success','Your income are updated.');
return redirect()->route('borrower.joint_declaration');
}
public function render()
{
$income_informations = DB::table('income_informations')->get();
$showDiv1 = $this->showDiv1;
$showDiv2 = $this->showDiv2;
$showDiv3 = $this->showDiv3;
$showDiv4 = $this->showDiv4;
return view('livewire.model-component',
[
'income_informations' => $income_informations,
'showDiv1'=>$showDiv1,
'showDiv2'=>$showDiv2,
'showDiv3'=>$showDiv3,
'showDiv4'=>$showDiv4,
]);
}
}
I created a variable to store the arrays because I realized that if I simply use the model name and then do updateOrCreate() it will probably only update the first one. But the result of that update function is that it updates the first row in the database, then creates a new row for the additional row, but I want it to update the other rows in the database instead.
For more context, I followed through this tutorial for the adding input fields and saving function. Now I have trouble trying to do the update function.
I've a table of building in which there is building name in db.when i add building through blade if the building name exist then it can not added. instead of storing it to db i want to show some error.what should i do?
this is my validation
$validator = Validator::make(
$request->all(),
[
'b_name' => 'required|max:20',
],
[
'b_name.required' => '*please fill this field',
]
);
if ($validator->fails()) {
return Response::make([
'message' => trans('validation_failed'),
'errors' => $validator->errors(),
]);
}
if ($validator->passes()) {
$name = $request->input('b_name');
$description = $request->input('b_description');
$created_at = Carbon::now();
$updated_at = Carbon::now();
$array = array('name' => $name, 'description' => $description, 'created_at' => $created_at, 'updated_at' => $updated_at);
Building::insert($array);
$validator = Validator::make(
$request->all(),
[
'b_name' => 'required|max:20|unique:buildings,name',
],
[
'b_name.required' => '*please fill this field',
'b_name.unique' => ('*building name already exists'),
]
);
if ($validator->fails()) {
return Response::make([
'message' => trans('validation_failed'),
'errors' => $validator->errors(),
]);
}
if ($validator->passes()) {
$name = $request->input('b_name');
$description = $request->input('b_description');
$created_at = Carbon::now();
$updated_at = Carbon::now();
$array = array('name' => $name, 'description' => $description, 'created_at' => $created_at, 'updated_at' => $updated_at);
Building::insert($array);
return 1;
}
Response::json(['errors' => $validator->errors()]);
}
If b_name is your input for building name and name is your database field name for Building model then try this code in your validation.
'b_name' => 'required|max:20|unique:App\Building,name'
For more details visit : https://laravel.com/docs/6.x/validation#rule-unique
Your code shoulde be like
$input = $request->all();
$rules = ['b_name' => 'required|required|unique:table_name,b_name|max:20'];
$messages = [
'b_name.required' => '*please fill this field'
'b_name.unique' => 'building name already taken.'
];
$validator = Validator::make($input, $rules, $messages);
I'm trying to make two functions in controller that have post action and that are in the same page.
My Controller
public function store(Request $request)
{
$status = DB::table('analytics')->where('dienstleistung', '!=', '')->get();
//Save data
$rules = [
'site_id' => 'required',
'dienstleistung' => 'required',
'objekt' => 'required',
'zimmer' => 'required',
'vorname' => 'required',
'name' => 'required',
'strasse' => 'required',
'ort' => 'required',
'plz' => 'required',
'tel' => 'required',
'email' => 'required|email',
'reinigungstermin' => 'required',
'gekommen' => 'required',
'message' => 'required',
'status' => 'required',
'answer' => 'required',
'notiz' => 'required',
'userId' => 'required',
];
$validator = Validator::make(Input::all(), $rules);
if($validator->fails()) {
return Redirect::to('anfrage')
->withErrors($validator)
->withInput();
}
else {
$anfrage = new Analytic();
$anfrage->site_id = Input::get('site_id');
$anfrage->dienstleistung = Input::get('dienstleistung');
$anfrage->objekt = Input::get('objekt');
$anfrage->zimmer = Input::get('zimmer');
$anfrage->vorname = Input::get('vorname');
$anfrage->name = Input::get('name');
$anfrage->strasse = Input::get('strasse');
$anfrage->ort = Input::get('ort');
$anfrage->plz = Input::get('plz');
$anfrage->tel = Input::get('tel');
$anfrage->email = Input::get('email');
$anfrage->reinigungstermin = Input::get('reinigungstermin');
$anfrage->gekommen = Input::get('gekommen');
$anfrage->message = Input::get('message');
$anfrage->status = Input::get('status');
$anfrage->answer = Input::get('answer');
$anfrage->notiz = Input::get('notiz');
$anfrage->userId = Input::get('userId');
try {
$anfrage->save();
flash()->success(trans('app.success'));
return Redirect::to('anfrage');
} catch (\Exception $e) {
Log::writeException($e);
return Redirect::to('anfrage')
->withErrors($e->getMessage())
->withInput();
}
}
}
public function editItem(Request $request) {
$anfrages = Analytic::find($request['id'] );
$anfrages->status = $request->status;
$anfrages->answer = $request->answer;
$anfrages->notiz = $request->notiz;
$anfrages->save();
return response ()->json( $anfrages );
}
My route:
Route::post('anfrage', 'AnfrageController#store');
Route::post ( 'anfrage', 'AnfrageController#editItem' );
EditItem function is OK, it makes changes when I want to edit data, but when I want to store data, message being displayed is:
creating default object from empty value
So, I need to leave active only one of these function, both are not working.
I try to create custom login page but I got an error
Undefined index: password
my controller code
$this->validate($Request, [
'Email' => 'required',
'password' => 'required',
]);
$email = $Request['Email'];
$password = md5($Request['password']);
$login = new login();
$login = login::where('Email', $email);
if(empty($password))
{
return('404');
}
if(Auth::attempt(['Email' => $Request->input('Email'), 'Password' =>$password]))
{
return ('ok');
}
return ('no');
any one help my to create custom login
this is my new code
but again i gor undefined::passsword
public function logincheck(Request $request)
{
$this->validate($request, [
'Email' => 'required',
'password' => 'required',
]);
$email = $request->Email;
$password = md5($request->get('password'));
if(Auth::attempt(['Email' => $request->get('Email'), 'Password' =>md5($request->get('password'))]))
{
return ('ok');
}
return ('no');
}
Your error comes from
$Request['password']
You are treating Request as an array. It's an object. You do
public funciton login(Request $request)
{
$password = $request->password;
//or use the global helper
$password = request('password');
//Attempt login
if(Auth::attempt(['Email' => $request->get('Email'), 'Password' =>$password]))
{
return ('ok');
}
}
Also if you follow Laravel tutorial properly, you don't need md5 to hash password. Auth::attemp() will hash it for you