Problem is how to validate by Database model, I have model "Emails". I just want to people can register if their email already in our Email model.
Email database table
Schema::create('emails', function (Blueprint $table) {
$table->increments('id');
$table->text('username')->nullable();
$table->text('fullname')->nullable();
$table->text('description')->nullable();
$table->text('email')->nullable();
$table->timestamps();
});
Auth#RegisterController
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|max:255|unique:users', here i guess
'password' => 'required|min:6|confirmed',
]);
}**strong text**
You have to use unique validation for unique email in users table and exists validation to check email exists in emails table.
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|max:255|unique:users|exists:emails',
'password' => 'required|min:6|confirmed',
]);
}
Assuming you have email field in both users and emails tables
Did u try RULE-EXISTS?
exists:table,column
The field under validation must exist on a given database table.
More:
https://laravel.com/docs/5.6/validation#rule-exists
Related
I am new to Laravel. I want to register the account so I have one form that has the details about the username, email, password, company name, and other company details. I got 2 tables in my database. Table 1 is the user table which is used to store the user details to log in like userID, email, password, and companyID (from table 2). Table 2 is the company table that stores company details. Table 2 has companyID, companyName, and so on. I want to ask how can I use one form to save my data in two different tables.
Here is the code from RegisterController
protected function create(array $data)
{
return User::create([
'username' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
First You Need To Insert In Company Table Then User Table Like This .
protected function create(array $data)
{
$company=Company::create([
'companyName'=>$data['companyName']
]);
User::create([
'username' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'companyID'=>$company->id
]);
}
Laravel has a very elegant solution for this. First you have to set the relations between both models. As it happens, your example can now cover both directions. That's why I now assume: a user can have many companies and a company only one user.
This means that in the user model you set the relation
protected function companies() {
return $this->hasMany(Company::class);
}
And in the Company Model you set this method:
protected function user() {
return $this->belongsTo(User::class);
}
Then in your controller, service etc. you can call the following:
$user = User::create([
'username' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
$company = [
'companyName' => 'fooBar',
];
$user->companies()->save($company);
Link to the doc: https://laravel.com/docs/5.1/eloquent-relationships#inserting-related-models
I want make register form by number, name, password with Laravel auth.
So I change username method in LoginController.php and validate method ,create method in RegisterController.php like following code.
But always show error
SQLSTATE[HY000]: General error: 1364 Field 'email' doesn't have a default value
LoginController
public function username()
{
return 'number';
}
RegisterController
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'number' => ['required'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
'password_confirmation' => ['required'],
]);
}
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'number' => $data['number'],
'password' => Hash::make($data['password']),
]);
}
I spent 2day for find registration customize authentication but I only see login customize.
I finded only one about registration customize.
But this page don't show solution.
https://laracasts.com/discuss/channels/laravel/user-registration-without-email?page=1
please help me.
Your User Model has email field that it:
requires
does not have default value when you try to create new user.
Go to your migrations create_users_table, and edit:
$table->string('email')->unique();
to
$table->string('email')->nullable();
But this is bad idea in my opinion, how will you identify those users later on? How will you let them reset their passwords?
I have been trying to create a record of a table B using the id of a created record in table A. But for some reason, the field is always null even though i have dumped the value of the model id and it's correct. but when i assign it to a field in table B it doesn't insert it. I don't get any errors, and both records are created(in Table A and B) but the value of the field that is supposed to have the ID of model A is NULL.
I have added the field to the $fillable array in the model class:
protected $fillable = [
'name', 'email', 'password', 'phone', 'role', 'A_id',
];
Here is the code I tried. Please help me solve this issue.
if($data['role'] == 'admin'){
$tableA = TableA::create([
'name' => $data['name'],
'phone' =>$data['phone']
]);
return TableB::create([
'A_id' => $tableA->id,
'name' => $data['nameB'],
'email' => $data['email'],
'role' => $data['role'],
'phone' => $data['phoneB'],
'password' => bcrypt($data['password']),
]);
}
Here is the migration file for TableB
public function up()
{
Schema::create('tableB', function (Blueprint $table) {
$table->increments('id');
$table->integer('A_id')->unsigned()->nullable();
$table->string('phone', 10)->unique();
$table->string('name');
$table->string('role');
$table->integer('address_id')->nullable();
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
$table->softDeletes();
});
}
Add A_id to the $fillable array in the TableB model:
protected $fillable = ['A_id', ......];
After Being confused for quite some time. I have tried a different way to create the model and for some reason, it's just working fine.
if($data['role'] == 'admin'){
$tableA = TableA::create([
'name' => $data['name'],
'phone' =>$data['phone']
]);
$tableB = new TableB();
$tableB->A_id = $tableA->id;
$tableB->name = $data['nameB'];
$tableB->email = $data['email'];
$tableB->role = $data['role'];
$tableB->phone = $data['phoneB'];
$tableB->password = bcrypt($data['password']);
$tableB->save();
return $tableB;
}
I am quite new to Laravel and I would like to ask if there is any possible way to store only 2 form fields inside a table while all of the data are stored inside one table at the same time.
For instance I have users table where is store the data from my form .
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
"role" => $data["role"],
]);
}
And this is my route.
Route::get('users/create', ["uses" => "UsersController#create"]);
I have tried this and it is not inserting the data into the second table.
protected function create2(array $data)
{
return User::create2([
"name" =>$data["name"],
"role" => $data["role"],
]);
}
Route:
Route::get('users/create2', ["uses" => "UsersController#create2"]);
What would I have to do to store at the same time only the role lets say and the name into a different table ?
UserController--> https://pastebin.com/8yjtLVar
RegisterController --> https://pastebin.com/DTiRJu3m
In the function create2,write:
protected function create2(array $data)
{
return User::create([
"name" =>$data["name"],
"role" => $data["role"],
]);
}
In the create2 function,write:
protected function create2(array $data)
{
return Userrole::create([
"name" =>$data["name"],
"role" => $data["role"],
]);
}
Make sure that Userrole model is created for usersrole table in the database.
I modified the default laravel's user table and I did that by creating my own migration.
Here's my migration sample:
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('username', 15)->unique()->after('id');
$table->string('lastname', 15)->unique()->after('username');
$table->string('firstname', 15)->unique()->after('lastname');
$table->string('contact')->nullable()->after('email');
$table->date('birthday')->after('contact');
$table->tinyInteger('status')->default(1)->after('birthday');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('username');
$table->dropColumn('lastname');
$table->dropColumn('firstname');
$table->dropColumn('contact');
$table->dropColumn('birthday');
$table->dropColumn('status');
});
}
And I removed the column name in the default laravel table so it looks like this:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
}
I checked the values from my form in the AuthController and I dont have an issue in getting the values. Here's what I added in the AuthController
protected $username = 'username'; //choose username instead of email
protected $redirectPath = '/dashboard'; //if successful login
protected $loginPath = 'auth/login'; //if not login
protected $redirectAfterLogout = 'auth/login'; //redirect after login
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'getLogout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'username' => 'required|min:8|max:16|unique:users',
'lastname' => 'required',
'firstname' => 'required',
'contact' => 'required',
'birthday' => 'date_format: Y-m-d',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
//dd($data); -- I can get all the values here
// I added my own column in this part to save. Is it correct?
return User::create([
'username' => $data['username'],
'lastname' => $data['lastname'],
'firstname' => $data['firstname'],
'birthday' => $data['birthday'],
'contact' => $data['contact'],
'email' => $data['email'],
'status' => 1,
'password' => bcrypt($data['password']),
]);
}
And when I try to save the data I can only save these columns
mysql> select * from users \G;
*************************** 1. row ***************************
id: 1
username:
lastname:
firstname:
email: myemail#gmail.com
contact: NULL
birthday: 0000-00-00
status: 1
password: $2y$10$3NkmqZaje4MKzheqPZKbhOIGD7ZlqYRfIP6DJZz4zb4gXVNvFsv2W
remember_token: PCYczF2Y9ts97TvbDOLsiXO5hxkekkxysmMYuIdN5MsaIY8TnroEof6d2jVM
created_at: 2015-09-17 06:56:43
updated_at: 2015-09-17 07:00:35
1 row in set (0.00 sec)
ERROR:
No query specified
How can I add my new column in the database?
Ok that's all I hope you can help me.
You can not edit the users table with this way
first, go to the terminal and write this command :
php artisan make:migration add_new_fields_to_users_table
and click enter.
After that, go to the migration file and in the add_new_fields_to_users_table.php
and write your new columns
$table->string('username', 15)->unique()->after('id');
$table->string('lastname', 15)->after('username');
$table->string('firstname', 15)->after('lastname');
$table->string('contact')->nullable()->after('email');
$table->date('birthday')->after('contact');
$table->tinyInteger('status')->default(1)->after('birthday');
Then , go to the terminal and do this:
php artisan migrate
and finally go to the User model and add the name's of your new table to the fillable variable
protected $fillable = [
'name', 'email', 'password','username',
'lastname','firstname','contact','birthday','status'
];
I hope this will help you
Ok I found the answer.
I need to put my own custom column in the fillable content:
protected $fillable = ['username', 'lastname', 'firstname', 'contact', 'email', 'birthday', 'status', 'password'];
Three files you need no adjust when you are adding new fields to the default users table or modifying to the default users table:
Users model found in Controllers\User.php or Controllers\Models\User.php
Update:
protected $fillable = [
'name',
'email',
'password',
];
Register blade in view located in views\auth\register.blade.php
Add new text-field for your new fields
Register Controller located at Controllers\Auth\RegisterController.php
Update:
Validator function and create function
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:8', 'confirmed'],
]);
}
protected function create(array $data)
{
return User::create([
'username' => $data['username'],
'email' => $data['email'],
'phone' => $data['phone'],
'password' => Hash::make($data['password']),
]);
}
Users table found in database\migrations\create_users_table.php
Add/Modify your schema
In the start I was able to add a role column to the users table like this.
public function up()
{
Schema::create('users', function (Blueprint $table) {
...
$table->string("role")->default("user");
...
});
}
I ran migrate and rollback commands several times while I was testing the application with different data. Later I needed two more columns in the user table.
Did as I had done before but failed.
Solved my problem with this artisan command and I was able to add more columns just by defining them in the user table schema as above.
Warning:
This rolls back all the migrations and you will lose all the data in your database. Make sure that you intentionally wanna happen this to the data.
php artisan migrate:reset