Laravel 5.1 Model Create - Column not found: 1054 - php

I am trying to register a user using User model and calling the create() method and passing array of inputs but getting Column not found: 1054.
public function postRegister(RegisterRequest $request)
{
$user = User::create([
'email' => $request->input('register-email'),
'password' => $request->input('register-password'),
'lastname' => $request->input('register-lastname'),
'firstname' => $request->input('register-firstname'),
]);
}
The keys inside the create() method is my database email, password, lastname, firstname and I added 'register-' in my html inputs because I have another form that use the name 'email and password'

so you can use the create method with array as a parameter, you must declare the columns in the fillable parameter
see: http://laravel.com/docs/5.1/eloquent#mass-assignment
you can also do it this way
$user = new User;
$user->email = $request->input('register-email');
$user->password = $request->input('register-password');
$user->lastname = $request->input('register-lastname');
$user->firstname = $request->input('register-firstname');
$user->save();

Related

Larave noting save hash password in database

My need create new user in admin dashboard, this store function, but database saving string not hash, please help.
When I output via dd(), then the hash working
`
public function store(Request $request)
{
$data = $request->validate([
'name' => 'required|string',
'email' => 'required|email|unique:users',
'password' => 'required|string|min:8|confirmed'
]);
$object = new Specialist();
$object->groups = 3;
$object->password = \Hash::make($data['password']);
$object->fill(request()->all());
$object->save();
return redirect()->route('specialists.index');
}
`
Model
`class Specialist extends Model
{
// USE DATABASE TABLE users
protected $table = 'users';
// FILL COLUMNS...
protected $fillable = ['email', 'password', 'name'];
}`
$object->fill(request()->all());
This line is overwriting the password field because request()->all() includes password.
Use except() method to remove the fields that you don't need:
$object->password = \Hash::make($data['password']);
$object->fill(request()->except('password'));

How can I fetch user ID after overriding it with different primary key in Eloquent ORM?

User model is returning id=null, while debug I found out the the reason behind this issue is that in my User model I override the $primary_key with a custom one
User Model
class User extends Authenticatable
{
use Notifiable;
// Set the primary key to the generated version instead of the regular ID
protected $primaryKey = 'user_code';
// Set the key type
protected $keyType = 'string';
// Diable the auto-increment option
public $incrementing = false;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'user_code',
'fname',
'mname',
'lname',
'email',
'dob',
'age',
'gender',
'insurance_number',
'ssn',
'avatar',
'is_active',
'userable_id',
'userable_type',
];
}
I have the following code that generate a new user_code that uses the id
$user = new User;
$user = $user->create([
'fname' => $request->fname,
'lname' => $request->lname,
'email' => $request->email,
]);
// Save the user in the DB
// Generate a usercode for the newely created user
$userCode = "ur" . date('y') . date('m') . $user->id;
Users Migration:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('user_code')->unique()->nullable();
$table->string('fname')->default('tbd');
$table->string('mname')->default('tbd');
$table->string('lname')->default('tbd');
$table->string('email')->unique()->nullable();
$table->date('dob')->default('1000-01-01');
$table->integer('age')->default(0);
$table->string('gender')->default('tbd');
$table->integer('insurance_number')->default(0);
$table->integer('ssn')->default(0);
$table->string('avatar')->default('tbd');
$table->boolean('is_active')->default(false);
$table->string('userable_code')->default('tbd');
$table->string('userable_type')->default('tbd');
$table->timestamp('email_verified_at')->nullable();
$table->rememberToken();
$table->timestamps();
});
$user->id is returning null, why such behavior is happening?
You've set $user as a new model instance:
$user = new User;
But then you're trying to create a new user from that instance, that won't work:
$user = $user->create([ ...
Since that doesn't work, you're not really saving anything to the DB, and you won't get an ID.
The second part of your problem is (as #TimLewis pointed out in the comments) that you are trying to create and save a model with a blank primary key (user_code). That won't work, so you'll need to work out what the ID is before trying to save it.
// Remove this line:
// $user = new User;
// Find the current highest ID:
$last = User::max('id');
// Your new user will have this ID
$newID = $last->id + 1;
// And just use the normal way to create and save a model:
$user = User::create([
'userCode' => "ur" . date('y') . date('m') . $newID,
'fname' => $request->fname,
'lname' => $request->lname,
'email' => $request->email,
]);
I may not know what you are trying to achieve here, but I'm just assuming that this is a very special use case.
Try this:
// Notice how we are using the User as a class, not instantiating it.
$user = User::create([
'fname' => $request->fname,
'lname' => $request->lname,
'email' => $request->email,
]);
// Save the user in the DB
// Generate a usercode for the newely created user
$userCode = "ur" . date('y') . date('m') . $user->id;
This assumes that your id column in your database table is still INCREMENTS and PRIMARY KEY

Laravel User Authentication Scaffolding -> Saving data into two tables

I am relatively new to laravel and have a project that requires a bit of manual configuration.
Background:
Working with Authentication Scaffolding (handles the user
registration and login)
I have two tables: Profile and Users.
All Users have one Profile.
But not all Profiles have a user.
Setup:
Profile table => id, name, avatar, etc.
User Table => profile_id, email, password
Since the Laravel Auth (Scaffold) handles the Registration and Login. I am trying to save data into the Profile table before saving the user table.
protected function create(array $data)
{
$profile = Profile::create
([
'slug' => $data['name'],
'name' => $data['name'],
]);
$user = User::create
([
'profile_id' => $profile->id,
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
return $user;
}
But this is not working. And the error message is telling me there is no profile_id assigned in the query.
What am I doing wrong?
How are your models set up? If Eloquent and your DB is set up correctly you can do this:
$profile = new Profile;
$profile->slug = $data['name'];
$profile->name = $data['name'];
$profile->save();
// At this point now you'll be able to get an ID of the profile
$user = new User;
$user->profile_id = $profile->id;
$user->name = $data['name'];
$user->email = $data['email'];
$user->password = bcrypt($data['password']);
$user->save();
return $user;

Bypassing email = unique:users in laravel

I am using Laravel 5.2, and I am trying to create a dashboard where the user can update his information, but I am facing one problem which is bypassing unique:users in validator.
if the user wants to keep same email, validator gives an error of 'The email has already been taken', also user should not change email to another email which is reserved by another user.
How can I avoid this validation in case if this user is the only user has this email.
my controller function:
public function update(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
// if fails, return response with errors
if($validator->fails())
return back()->withErrors($validator)->withInput();
$user = Auth::user();
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->password = bcrypt($request->input('password'));
$user->update();
return back()->withInput();
}
Laravel's unique validator can take additional parameters that can help you exclude given ID from the unique check.
The syntax is:
unique:<table>,<column>,<id_to_exclude>
In your case, you'll need the follwing validation rule:
'email' => 'required|email|max:255|unique:users,email,'.$id
Just change your code to:
public function update(Request $request)
{
$id = Auth::user()->id;
$validator = Validator::make($request->all(), [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users'.$id,
'password' => 'required|min:6|confirmed',
]);
// if fails, return response with errors
if($validator->fails())
return back()->withErrors($validator)->withInput();
$user = Auth::user();
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->password = bcrypt($request->input('password'));
$user->update();
return back()->withInput();
}
Why this works? Well the laravel Unique validation searches for the unique value in the table specified. So unique:users searches if the email exists in db. The user id here works as a way to exclude the check for this user.
Also, if you want that email should not be edited, then just exclude it from the request.
$input = $request->excpet(['email']); check docs

how to check if a user email already exist

In laravel, when a new user is registering to my site and the email they use already exist in the database. how can tell the user that the email already exist ?. I am new to laravel framework. A sample code would be nice too.
The validation feature built into Laravel lets you check lots of things, including if a value already exists in the database. Here's an overly simplified version of what you need. In reality you'd probably want to redirect back to the view with the form and show some error messages.
// Get the value from the form
$input['email'] = Input::get('email');
// Must not already exist in the `email` column of `users` table
$rules = array('email' => 'unique:users,email');
$validator = Validator::make($input, $rules);
if ($validator->fails()) {
echo 'That email address is already registered. You sure you don\'t have an account?';
}
else {
// Register the new user or whatever.
}
);
Laravel has built-in human readable error messages for all its validation. You can get an array of the these messages via: $validator->messages();
You can learn more about validation and what all you can do with it in the Laravel Docs.
Basic Usage Of Unique Rule
'email' => 'unique:users'
Specifying A Custom Column Name
'email' => 'unique:users,email_address'
Forcing A Unique Rule To Ignore A Given ID
'email' => 'unique:users,email_address,10'
Adding Additional Where Clauses
You may also specify more conditions that will be added as "where" clauses to the query:
'email' => 'unique:users,email_address,NULL,id,account_id,1'
The above is from the documentation of Laravel
You could add:
public static $rules = [
'email' => 'unique:users,email'
];
You can add more rules to the $rules like:
public static $rules = [
'email' => 'required|unique:users,email'
];
It will automatically produce the error messages
and add:
public static function isValid($data)
{
$validation = Validator::make($data, static::$rules);
if ($validation->passes())
{
return true;
}
static::$errors = $validation->messages();
return false;
}
to the model User.php
Then in the function you're using to register, you could add:
if ( ! User::isValid(Input::all()))
{
return Redirect::back()->withInput()->withErrors(User::$errors);
}
if(sizeof(Users::where('email','=',Input::get('email'))->get()) > 0) return 'Error : User email exists';
The great resource is only Laravel Documentation #
enter link description here
I also did like below when integrating user management system
$user = Input::get('username');
$email = Input::get('email');
$validator = Validator::make(
array(
'username' => $user,
'email' => $email
),
array(
'username' => 'required',
'email' => 'required|email|unique:users'
)
);
if ($validator->fails())
{
// The given data did not pass validation
echo 'invalid credentials;';
// we can also return same page and then displaying in Bootstap Warning Well
}
else {
// Register the new user or whatever.
$user = new User;
$user->email = Input::get('email');
$user->username = Input::get('username');
$user->password = Hash::make(Input::get('password'));
$user->save();
$theEmail = Input::get('email');
// passing data to thanks view
return View::make('thanks')->With('displayEmail', $theEmail);
}
public function userSignup(Request $request, User $data){
# check user if match with database user
$users = User::where('email', $request->email)->get();
# check if email is more than 1
if(sizeof($users) > 0){
# tell user not to duplicate same email
$msg = 'This user already signed up !';
Session::flash('userExistError', $msg);
return back();
}
// create new files
$data = new User;
$data->name = $request->name;
$data->email = $request->email;
$data->password = md5($request->password);
$data->save();
//return back
Session::flash('status', 'Thanks, you have successfully signup');
Session::flash('name', $request->name);
# after every logic redirect back
return back();
}
I think when u try something like this you earn a smooth check using Model
We can use the Validator.
In your Controller.
$validator = $request->validate([
'name' => 'required',
'phone' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required',
]);
In View
#error('email') <span class="text-danger error">{{ $message }}</span>#enderror
$this->validate($request, [
'fname' => 'required',
'lname' => 'required',
'email' => 'required|min:4|email|unique:users',
'password' => 'required',
]);
Try This

Categories