Not saving user data to users table in laravel 5.6 - mysql

I am going to insert new data records to users table in laravel 5.6. this is My UserController,
public function store(Request $request)
{
$this->validate($request,[
'name' => 'required|max:255',
'userlevel' => 'required',
'email' => 'required|email|unique:users',
]);
$user = new User();
$user->name = $request->input('name');
$user->uservalue = $request->input('uservalue');
$user->email = $request->input('email');
$user->password = $request->input(bcrypt($data['password']));
$user->save();
return redirect()->route('users.show', $user->id);
}
and blade file is,
<form action="{{route('users.store')}}" method="POST">
{{csrf_field()}}
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Enter Name">
</div>
<div class="form-group">
<label for="exampleFormControlSelect1">User Level</label>
<select class="form-control" id="uservalue" name="uservalue">
<option>0</option>
<option>2</option>
<option>1</option>
</select>
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" class="form-control" id="email" name="email" placeholder="Enter Email">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="text" class="form-control" id="password" name="password" placeholder="Enter Password">
</div>
<button type="submit" class="btn btn-primary">Create User</button>
</form>
</div>
route is,
Route::resource('/users','UserController');
But when I clicked submit button data not saving to users table. not any error message occurred. only refresh page. how can fixed this problem?

public function store(Request $request)
{
$this->validate($request,[
'name' => 'required|max:255',
'uservalue' => 'required',
'email' => 'required|email|unique:users',
]);
$user = new User();
$user->name = $request->input('name');
$user->uservalue = $request->input('uservalue');
$user->email = $request->input('email');
$user->password = $request->input(bcrypt($data['password']));
$user->save();
return redirect()->route('users.show', $user->id);
}
please Change userlevel to uservalue

I think the problem is here $request->input(bcrypt($data['password'])) You are passing $data but not defining it. simply try this: bcrypt($request->input('password'))
Also, you are validating userlevel but inserting uservalue.

Related

Attempt to read property "name" on array

I am trying to enter data inside database table via form. I have created an instance of Model and accessed the columns of that table and assigned the input names of form but when I enter data an submit it says Attempt to read property "name" on array. Can anyone guide me if there is anything wrong.
Code of Controller where im inserting datas to database
class UserController extends Controller
{
function registerUser(Request $req)
{
$data = $req->input();
$user_model = new User;
$user_model->fullname = $data->name;
$user_model->mobile = $data->mobile;
$user_model->email = $data->email;
$user_model->password = $data->password;
$user_model->save();
return "registered successfully";
}
}
Code of Form
<div class="register-form">
<h4>Sign Up</h4>
<form method="post" action="register">
#csrf
<input type="text" name="name" placeholder="Full Name" size="40">
<br>
<input type="tel" name="mobile" placeholder="Mobile number" size="40">
<br>
<input type="email" name="email" placeholder="Email" size="40">
<br>
<input type="password" name="password" placeholder="Password" size="40">
<br>
<input id="submit_btn" type="submit" placeholder="Sign Up" size="40">
<hr>
<p>Already, have an account <span href="#" id="sign-in-link">Log In</span></p>
</form>
</div>
function registerUser(Request $req)
{
$user_model = new User;
$user_model->fullname = $req->name;
$user_model->mobile = $req->mobile;
$user_model->email = $req->email;
$user_model->password = bcrypt($req->password); //laravel hashed password
$user_model->save();
return "registered successfully";
}
$req->input is an array. Access it like so.
$user_model->fullname = $data['name'];
$user_model->mobile = $data['mobile'];
$user_model->email = $data['email'];
$user_model->password = $data['password'];

Failed to store data in laravel 8

I'm making a form so that users can request to create a new account to the admin, but every time I try to send data, it always fails, even though I've checked every part of my code, can anyone help me?
the form code :
<form method="POST" action="{{ url('/request-akun/make-request') }}">
#csrf
<div class="form-group col-md-12">
<label for="name">Nama</label>
<input type="text" name="name" class="form-control" id="name">
</div>
<div class="form-group col-md-12">
<label for="email">Email</label>
<input type="text" name="email" class="form-control" id="email">
</div>
<div class="form-group col-md-12">
<label for="password">Password</label>
<input type="text" name="password" class="form-control"
id="password">
</div>
<div class="form-group col-md-12">
<label for="password_confirm">Konfirmasi Password</label>
<input name="password_confirm" type="text" class="form-control"
id="password">
</div>
<button type="submit" class="btn btn-primary pull-right"
style="margin-right: 15px;">Request</button>
</form>
this is the controller :
public function requestAccount(Request $request){
$request->validate([
'name' => 'required|string|max:255',
'ra_instansi_id' => 'required',
'email' => 'required|string|email|max:255',
'password' => 'required',
'password_confirm' => 'required'
]);
if ($request->get('password') == $request->get('password_confirm')){
$data = new requestAkun();
$data->name = $request->get('name');
$data->ra_user_id = Auth::id();
$data->ra_instansi_id = Auth::user()->instansiID;
$data->email = $request->get('email');
$data->password = $request->get('password');
$data->status = "pending";
$data->save();
return Redirect::to('/request-akun/request-lists')->with('success','Request Berhasil dikirim');
} else {
return Redirect::to('/request-akun/request-lists')->with('error','Password tidak sama');
}
}
this is the model code:
class requestAkun extends Model
{
use HasFactory, Uuids;
protected $table = 'request_akun';
public $timestamps = true;
protected $fillable = [
'name',
'ra_instansi_id',
'ra_user_id',
'email',
'password',
'status'
];
}
this is the route :
Route::prefix('request-akun')->group(function(){
Route::post('/make-request',[userController::class,'requestAccount'])->name('make-request');
});
Error is you don't have ra_instansi_id input in your form.
Not showing any validation error message in your form so better show errors so you check which validation failed.
3.Instead of checking password match in if condition you can change input name password_confirm to password_confirmation so you can change like below
<input name="password_confirmation" type="text" class="form-control"
id="password_confirmation">
and in your validation
$validator=Validator::make($request->all(),[
'name' => 'required|string|max:255',
'ra_instansi_id' => 'required',
'email' => 'required|string|email|max:255',
'password' => 'required|confirmed',
'password_confirmation' => 'required'
]);
dd($validator->errors());

Having issues accessing data from my service in Angular

I'm trying to access and use the data from my service and having some issues. I am able to see the data returned just fine in the console from my console.log(data); from the method below:
public getCustomerData() {
this.Service.getCustomers().subscribe((data) => {
console.log(data);
this.customers = data.value;
console.log(this.customers);
var i:number;
for(i = 0; i < this.customers.length; i++ ){
if(this.customers[i].CityName == null || this.customers[i].StateName == null || this.customers[i].ZipCode == null || this.customers[i].Address1 == null){
this.customers[i].Address1 = "";
this.customers[i].CityName = "San Diego";
this.customers[i].StateName = "California";
this.customers[i].ZipCode = "12345";
}
}
})
}
Where I am running into issues is the next line this.customers = data.value;, I am recieving the error Property 'value' does not exist on type 'Customer[]'.
Here is how my data is returned:
Service method:
public getCustomers()
{
let url = "https://rss-staging.carefusion.com/api/odata/Facilities";
const params = new HttpHeaders()
.set('X-Atlas-SecurityKey', '75162FD1-A4E8-40AB-A62A-823932CEAD1F')
return this.http.get<Customer[]>(url, {headers: params})
}
HTML Table:
<div class="row pb-2">
<div class="col-lg-4">
<div class="form-group">
<label for="input1">Name</label>
<input type="text" placeholder="Customer Name" class="form-control" id="input1"
aria-describedby="Text field" name="name" [(ngModel)]="fields.Name"
(ngModelChange)="updateFilters()" />
</div>
</div>
<div class="col-lg-5">
<div class="form-group">
<label for="input1">Address</label>
<input type="text" placeholder="Customer Address" class="form-control" id="input1"
aria-describedby="Text field" name="address" [(ngModel)]="fields.Address1"
(ngModelChange)="updateFilters()" />
</div>
</div>
</div>
<div class="row pb-2">
<div class="col-lg-3">
<div class="form-group">
<label for="input1">City</label>
<input type="text" placeholder="City" class="form-control" id="input1" aria-describedby="Text field"
name="city" [(ngModel)]="fields.CityName" (ngModelChange)="updateFilters()" />
</div>
</div>
<div class="col-lg-3">
<div class="form-group">
<label for="input1">State</label>
<input type="text" placeholder="State" class="form-control" id="input1" aria-describedby="Text field"
name="name" [(ngModel)]="fields.StateName" (ngModelChange)="updateFilters()" />
</div>
</div>
<div class="col-lg-3">
<div class="form-group">
<label for="input1">Zip Code</label>
<input type="text" placeholder="123456" class="form-control" id="input1" aria-describedby="Text field"
name="name" [(ngModel)]="fields.ZipCode" (ngModelChange)="updateFilters()" />
</div>
</div>
</div>
How can I fix this?
From the code, I can see that you have typecasted the result of the function getCustomers() to customers[]
return this.http.get<Customer[]>(url, {headers: params})
Basically you are returning an array of customers from the http call.
To return correct value, pipe the results and map
import { map } from 'rxjs/operators'
return this.http.get<any>(url, {headers: params}).pipe(
map(data => data.value as Customer[])
)
Your method getCustomers() from the service already return a list of customers, and a list doesn't have a property called value.
You only have to do this, and should works.
this.customers = data;

How to Send Multiple Checkbox through migration in LARAVEL_7

I want to store the selected checks in a single variable and send it to the database, I am only using migrations, others that other data is sent in the migration.
Pd: I get this error by the array:
ErrorException
Array to string conversion
My template.
<form action="{{ route('save') }}" method="POST">
#csrf
<div class="row">
<div class="col-md-6 mt-5">
<select name="Sede" class="form-select" aria-label="Default select example">
<option selected name="Sede">Campus Sede</option>
<option value="Cancún">Cancún</option>
<option value="Chihuahua">Chihuahua</option>
</select>
</div>
<div class="col-md-6 mt-5">
<select name="Alcance" class="form-select" aria-label="Default select example">
<option selected name>Alcance</option>
<option value="Local">Local</option>
<option value="Nacional">Nacional</option>
</select>
</div>
<div class="col-md-6 mt-5">
<label for="">Nombre del Proyecto</label>
<input type="text" name="Nombre" class="form-control col-12">
</div>
<div class="col-md-6 mt-5">
<label for="">Cierre de Inscripciones</label>
<input data-date-format="yyyy/mm/dd" id="datepicker" name="Cierre" class="form-control col-12">
</div>
<div class="col-md-6 mt-5">
<input type="checkbox" name="Areas[]"id="ingenieria" value="Ingeniería" />
<label for="ingenieria">Ingeniería</label>
<input type="checkbox" name="Areas[]"id="humanidades" value="Humanidades" />
<label for="humanidades">Humanidades</label>
<input type="checkbox" name="Areas[]"id="negocios" value="Negocios" />
<label for="negocios">Negocios</label>
<input type="checkbox" name="Areas[]" id="salud" value="Salud" />
<label for="salud">Salud</label>
</div>
<div class="col-md-12 mt-5">
<label for="">Cual es el departamento donde impactara directamente el proyecto?</label>
<input type="text" name="P1" class="form-control col-12">
</div>
<div class="row form-group mt-5">
<button type="submit" class="btn btn-success col-md-2 offset-5">Guardar</button>
</div>
</form>
My controller:
public function save(Request $request){
$validator = $this->validate($request, [
'Sede'=> 'required|string|max:255',
'Alcance'=> 'required|string|max:255',
'Nombre'=> 'required|string|max:255',
'Cierre'=> 'required|date',
'Areas'=> 'required',
'P1'=> 'required|string|max:255',
'P2'=> 'required|string|max:255',
'P3'=> 'required|string|max:255',
'P4'=> 'required|string|max:255'
]);
$data = request()->except('_token');
Project::insert($data);
return back()->with('datosGuardados', 'Datos almacenados, Correctamente');
}
My Model:
class Project extends Model
{
protected $fillable = ['Sede','Alcance','Nombre','Cierre','Areas','P1','P2','P3','P4'];
protected $casts = [
'Areas' => 'array'
];
}
My migration:
public function up()
{
Schema::create('projects', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('Sede');
$table->string('Alcance');
$table->string('Nombre');
$table->date('Cierre');
$table->string('Areas');
$table->string('P1');
$table->string('P2');
$table->string('P3');
$table->string('P4');
$table->timestamps();
});
}
enter image description here
As you see the error is due to the checkbox that I don't know how to send it as a single array and store it in the database, I would appreciate any help. I was investigating and I did not find anything
$validator = $this->validate($request, [
'Sede'=> 'required|string|max:255',
'Alcance'=> 'required|string|max:255',
'Nombre'=> 'required|string|max:255',
'Cierre'=> 'required|date',
'Areas'=> 'required',
'P1'=> 'required|string|max:255',
'P2'=> 'required|string|max:255',
'P3'=> 'required|string|max:255',
'P4'=> 'required|string|max:255'
]);
// Add this line
$area = [];
foreach ($request->Areas as $key => $value) {
$area[$key] = $value;
}
// And then save in database with $area created using foreach.
Use this 'Areas.*'=> 'required', for validating the checkbox generally, moreover to insert the data under Areas, you can insert it via converting by json_encode($request->Areas);

Having an issue inputting values into DB with PDO

So this is the PHP code that processes the form info and it supposed to send data into the DB. It is successful every time and shoots me a success message but when I look in database I see a new row but no actual data from the form.
REMINDER: the db connection is working, except it's sending blank values to fill up the table as opposed to the form data.
Here is the HTML form to be handled by the PHP code in dealer.php:
<form action="dealer.php" method="POST">
<div class="form-group">
<label for="company">Company Name</label>
<input type="text" class="form-control" id="company" name="company" placeholder="Company Name">
</div>
<div class="form-group">
<label for="location">Location</label>
<input type="text" class="form-control" id="location" name="location" placeholder="Location">
</div>
<div class="form-group">
<label for="founded">Founded</label>
<input type="text" class="form-control" id="founded" name="founded" placeholder="Founded">
</div>
<div class="form-group">
<label for="employees"># of Employees</label>
<input type="text" class="form-control" id="employees" name="employees" placeholder="# of employees">
</div>
<div class="form-group">
<label for="employees"># of Employees</label>
<input type="text class="form-control" id="sales" name="sales" placeholder="2014 sales">
</div>
<div class="radio">
<label><p>Is the company traded publicly?</p>
<input type="radio" name="optionsRadios" name="public" id="Yes" value="Yes">
Yes
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="optionsRadios" name="public" id="No" value="No">
No
</label>
</div>
<div class="form-group">
<label class="sr-only" for="gross_2014">Gross Revenue</label>
<div class="input-group">
<div class="input-group-addon">$</div>
<input type="text" class="form-control" id="gross_2014" name="gross_2014" placeholder="Gross Revenue">
<div class="input-group-addon">.00</div>
</div>
</div>
<div class="form-group">
<label class="sr-only" for="net_2014">Net Revenue</label>
<div class="input-group">
<div class="input-group-addon">$</div>
<input type="text" class="form-control" id="net_2014" name="net_2014" placeholder="Net Revenue">
<div class="input-group-addon">.00</div>
</div>
</div>
<div class="form-group">
<label class="sr-only" for="growth_2014">Growth(%)</label>
<div class="input-group">
<div class="input-group-addon">%</div>
<input type="text" class="form-control" id="growth_2014" name="growth_2014" placeholder="Growth %">
<div class="input-group-addon">.00</div>
</div>
</div>
<textarea class="form-control" rows="3"></textarea>
<div class="form-group">
<p class="help-block" id="customer" name="customer">Customer profile info... </p>
</div>
<textarea class="form-control" rows="3"></textarea>
<div class="form-group">
<p class="help-block" id="products" name="products">Info about product offerings.</p>
</div>
<div class="checkbox">
<label>
<input type="checkbox"> Check me out
</label>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
And here are the contents of dealer.php that process the HTML form above:
<?php
$servername = "XX.XXX.XXX.XX";
$username = "smartkrawl";
$password = "Bondurant15!";
$dbname = "smartkrawl";
class companyInfo{
public $name;
public $location;
public $founded;
public $employees;
public $sales;
public $gross_2014;
public $net_2014;
public $growth_2014;
public function __construct($name,$location,$founded,$employees,$sales,$gross_2014, $net_2014, $growth_2014) {
$this->name = $name;
$this->location = $location;
$this->founded = $founded;
$this->employees = $employees;
$this->sales = $sales;
$this->gross_2014 = $gross_2014;
$this->net_2014 = $net_2014;
$this->growth_2014 = $growth_2014;
}
}
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO companyInfo (name, location, founded, employees, sales, gross_2014, net_2014, growth_2014)
VALUES ('$name', '$location', '$founded', '$employees', '$sales', '$gross_2014', '$net_2014', '$growth_2014')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
You didn't get the POST values in your php code, that's why the columns of the row are empty. The variables are not set.
I don't think you should use a class just to handle a form, it's unnecessary.
Since you getting this data from a form, it's good to security the use of prepared statements to insert the data. You're already using PDO, so you can just use the prepared statements without problem.
You can read about PDO Prepared Statements on PHP Manual (http://php.net/manual/en/pdo.prepared-statements.php)
I modified your code and now should be working.
<?php
$name = $_POST['company'];
$location = $_POST['location'];
$founded = $_POST['founded'];
$employees = $_POST['employees'];
$sales = $_POST['sales'];
$gross_2014 = $_POST['gross_2014'];
$net_2014 = $_POST['net_2014'];
$growth_2014 = $_POST['growth_2014'];
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = $conn->prepare("INSERT INTO companyInfo (name, location, founded, employees, sales, gross_2014, net_2014, growth_2014) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
$sql->bindValue(1, $name);
$sql->bindValue(2, $location);
$sql->bindValue(3, $founded);
$sql->bindValue(4, $employees);
$sql->bindValue(5, $sales);
$sql->bindValue(6, $gross_2014);
$sql->bindValue(7, $net_2014);
$sql->bindValue(8, $growth_2014);
$exec = $sql->execute();
if($exec) {
echo "New record created successfully";
}
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
By the way, in your HTML code, there's a quote missing on this line after the type attribute.
<input type="text class="form-control" id="sales" name="sales" placeholder="2014 sales">
Replace by
<input type="text" class="form-control" id="sales" name="sales" placeholder="2014 sales">
And there's a field on the form that you didn't set on your PHP code, which is the optionsRadios radio. I didn't put that radio in the code because you didn't put it on the original code. So, if you want to put it there, just add it on the PHP like any other field.