How to add new column in Laravel's default Users table? - laravel

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

Related

LARAVEL: SQLSTATE[HY000]: General error: 1364 Field 'created_at' doesn't have a default value

I've tried to create an admin module for a schoolproject with laravel.
I copied all the authentication stuff to register a person, but changed everything so it's a a different module. However, I can't seem to fix this problem. It always says that my 'created_at' doesn't have a default value. But it has the timestamp() module so I would think that it doesn't need anything else. Anyone who sees the fault.
My Migration:
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('admins', function (Blueprint $table) {
$table->increments('admin_id');
$table->string('naam');
$table->string('email')->unique;
$table->binary('password');
$table->enum('rol', ['user','admin'])->default('admin');
$table->timestamp('created_at')->nullable();
$table->timestamp('updated_at')->nullable();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('admins');
}
};
My model
class Admin extends Model
{
use HasFactory;
protected $table = 'admins';
protected $primaryKey = 'admin_id';
protected $fillable =
[
'admin_id',
'naam',
'email',
'password',
'rol',
];
public $timestamps = false;
}
My Controller
class RegisteredUserController extends Controller
{
/**
* Display the registration view.
*
* #return \Illuminate\View\View
*/
public function create()
{
return view('auth.register');
}
/**
* Handle an incoming registration request.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*
* #throws \Illuminate\Validation\ValidationException
*/
public function store(Request $request)
{
$request->validate([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'confirmed', 'min:5'],
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
event(new Registered($user));
Auth::login($user);
return redirect(RouteServiceProvider::HOME);
}
public function createAdmin()
{
return view('auth.registeradmin');
}
public function storeAdmin(Request $request)
{
$request->validate([
'naam' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'confirmed', 'min:5'],
]);
$admin = Admin::create([
'naam' => $request->naam,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
event(new Registered($admin));
Auth::login($admin);
return redirect(RouteServiceProvider::HOME);
}
}

Jetstream unable to delete account after modifying the authentication logic. (Laravel 9,Jetstream, Inertia, VueJs3)

Recently I have decided to add another field when in log in page( Username ), it is unique.
When log in you can use either username or email to do so.
After the modification, "Login", "Registeration", "Changing Password", "Password Reset", "Email Verification" worked fine.
"Two Factor Authentication", "Browser Sessions", "Delete Account" does not working just wondering what has gone wrong
When i try to delete account or log out from all browser session, this pops out
for more detailed error https://flareapp.io/share/17DK4R9P#F73
config/fortify
'username' => 'auth',
'email' => 'email',
Models/User.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use JoelButcher\Socialstream\HasConnectedAccounts;
use JoelButcher\Socialstream\SetsProfilePhotoFromUrl;
use Laravel\Fortify\TwoFactorAuthenticatable;
use Laravel\Jetstream\HasProfilePhoto;
use Laravel\Jetstream\HasTeams;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use App\Models\Post;
class User extends Authenticatable implements MustVerifyEmail
{
use HasApiTokens;
use HasFactory;
use HasProfilePhoto {
getProfilePhotoUrlAttribute as getPhotoUrl;
}
use HasTeams;
use HasConnectedAccounts;
use Notifiable;
use SetsProfilePhotoFromUrl;
use TwoFactorAuthenticatable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'username'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
'two_factor_recovery_codes',
'two_factor_secret',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* The accessors to append to the model's array form.
*
* #var array
*/
protected $appends = [
'profile_photo_url',
];
/**
* Get the URL to the user's profile photo.
*
* #return string
*/
public function getProfilePhotoUrlAttribute()
{
if (filter_var($this->profile_photo_path, FILTER_VALIDATE_URL)) {
return $this->profile_photo_path;
}
}
Users database
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->string('username')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password')->nullable();
$table->rememberToken();
$table->foreignId('current_team_id')->nullable();
$table->foreignId('current_connected_account_id')->nullable();
$table->foreignId('current_connected_post_id')->nullable();
$table->text('profile_photo_path')->nullable();
$table->timestamps();
});
}
}
}
action/fortify/UpdatesUserProfileInformation.php
Validator::make($input, [
'name' => ['required', 'string', 'max:255'],
'username' => ['required', 'string', 'max:255', 'alpha_dash:users', Rule::unique('users')->ignore($user->id)],
'email' => ['required', 'email', 'max:255', Rule::unique('users')->ignore($user->id)],
'photo' => ['nullable', 'mimes:jpg,jpeg,png', 'max:10024'],
])->validateWithBag('updateProfileInformation');
action/fortify/CreatesNewUsers.php
Validator::make($input, [
'name' => ['required', 'string', 'max:255'],
'username' => ['required', 'string', 'max:255', 'unique:users','alpha_dash:users'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => $this->passwordRules(),
'terms' => Jetstream::hasTermsAndPrivacyPolicyFeature() ? ['required', 'accepted'] : '',
])->validate();
return DB::transaction(function () use ($input) {
return tap(User::create([
'name' => $input['name'],
'email' => $input['email'],
'username' => $input['username'],
'password' => Hash::make($input['password']),
]), function (User $user) {
$this->createTeam($user);
});
});
provides/fortifyserviceprovider.php
Fortify::authenticateUsing(function (LoginRequest $request) {
$user = User::where('email', $request->auth)
->orWhere('username', $request->auth)->first();
if (
$user &&
Hash::check($request->password, $user->password)
) {
return $user;
}
});
provides/jetstreamserviceprovider.php
Fortify::authenticateUsing(function (LoginRequest $request) {
$user = User::where('email', $request->auth)
->orWhere('username', $request->auth)->first();
if (
$user &&
Hash::check($request->password, $user->password)
) {
return $user;
}
});
I have found the solution for all this,
Inside vendor/laravel/fortify/src/Actions/ConfirmPassword.php, there is a function __invoke which Confirm that the given password is valid for the given user.
In default, $username = config('fortify.username'); but my config('fortify.username') is set to auth that why it is not inside the database and return column not found
Is there a way to change this? cuz modifying the vendor is not a good solution.
You can do this in two ways and override the required items in Fortify
app()->singleton(ConfirmPassword::class, MyConfirmPassword::class);
or
// custom hook for confirming passwords
Fortify::confirmPasswordsUsing(function($user, $password) {
// your code!;
});

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null?

I got this error when try to seed database.
Laravel 7.
BlogPost Model
class BlogPost extends Model
{
protected $fillable = [
'title',
'slug',
'user_id',
'category_id',
'excerpt',
'content_raw',
'content_html',
'is_published',
'published_at',
'updated_at',
'created_at',
];
public function category()
{
return $this->belongsTo(BlogCategory::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
}
User model
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
User migration
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
BlogPost migration
Schema::create('blog_posts', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('category_id');
$table->foreignId('user_id')->constrained();
$table->string('title');
$table->string('slug')->unique();
$table->text('excerpt')->nullable();
$table->text('content_raw');
$table->text('content_html');
$table->boolean('is_published')->default(false)->index();
$table->timestamp('published_at')->nullable();
$table->foreign('category_id')->references('id')->on('blog_categories');
$table->timestamps();
});
User seeder
class UserTableSeeder extends Seeder
{
public function run()
{
$users = [
[
'name' => 'Author',
'email' => 'seriiburduja#mail.ru',
'password' => bcrypt('some1234')
],
[
'name' => 'Admin',
'email' => 'seriiburduja#gmail.com',
'password' => bcrypt('some1234')
]
];
DB::table('users')->insert($users);
}
}
BlogPost Factory
$factory->define(BlogPost::class, function (Faker $faker) {
$title = $faker->sentence(rand(3, 8), true);
$text = $faker->realText(rand(1000, 4000));
$isPublished = rand(1, 5) > 1;
$createdAt = $faker->dateTimeBetween('-6 months', '-1 day');
return [
'category_id' => rand(1, 10),
'user_id' => 1,
'title' => $title,
'slug' => Str::slug($title),
'excerpt' => $faker->text(rand(100, 400)),
'content_raw' => $text,
'content_html' => $text,
'is_published' => $isPublished,
'published_at' => $isPublished ? $faker->dateTimeBetween('-6 months', '-1day') : null,
'created_at' => $createdAt,
'updated_at' => $createdAt
];
});
DatabaseSeeder
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
$this->call(UserTableSeeder::class);
$this->call(BlogCategorySeeder::class);
factory(BlogPost::class, 1)->create();
}
}
When i run php artisan migrate:fresh --seed i got this error.
Tables users and blog_categories seeds successfully, but error appear for blog_categories.
I don't understand why.
Field user_id exists in $fillable in BlogPost Model.
If i change migration for blog_posts and add a nullable for user_id, than seed work, but user_id is null. But i don't need that.
Thansk in advance.
In Blog Post Model
Change user relationship to
public function owner()
{
return $this->belongsTo(User::class);
}
In User Model
Add this relationship
public function blogposts()
{
return $this->hasMany(BlogPost::class);
}
In Database seeder don't use UserSeeder Directly create user in DatabaseSeeder
public function run()
{
$user = User::create([
'name' => "Your name",
'email' => "youremail#gmail.com",
'password' => Hash::make('YourPassword')
]);
$this->call(BlogCategorySeeder::class);
$user->blogposts()->saveMany(BlogPost::factory(1));
}
In BlogPost Factory remove user_id
return [
'category_id' => rand(1, 10),
'title' => $title,
'slug' => Str::slug($title),
'excerpt' => $faker->text(rand(100, 400)),
'content_raw' => $text,
'content_html' => $text,
'is_published' => $isPublished,
'published_at' => $isPublished ? $faker->dateTimeBetween('-6 months', '-1day') : null,
'created_at' => $createdAt,
'updated_at' => $createdAt
];
fillable is not required when you are using Seeder to insert data.
If you want to insert each and every column in database then you can use guarded property which is opposite of fillable.

Laravel validation by database records

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

Laravel "Cannot add foreign key constraint" - Migrate

I have a problem with a foreign key.
I have a user who has a sex:
My migration users :
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('nom');
$table->string('prenom');
$table->string('adresse');
$table->integer('cp');
$table->string('ville');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
$table->tinyInteger('admin')->nullable();
});
Schema::table('users', function ($table) {
$table->integer('sexe_id')->unsigned();
$table->foreign('sexe_id')->references('id')->on('sexes');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('users');
}`
My sexe migration :
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('sexes', function (Blueprint $table) {
$table->increments('id');
$table->string('libelle');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('sexes');
}
My sexes seeder :
class SexesTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
DB::table('sexes')->insert([
[
'libelle' => 'Homme',
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
],
[
'libelle' => 'Femme',
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
]
]);
}
}
My users seeder :
class UsersTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
DB::table('users')->insert([
[
'name' => 'admin',
'nom' => 'Virlois',
'prenom' => 'Peter',
'sexe_id' => 1,
'email' => 'admin#admin.fr',
'adresse' => '12 rue Jean Rostand',
'cp' => 90000,
'ville' => 'Belfort',
'password' => bcrypt('admin123'),
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
'admin' => 1,
],
[
'name' => 'test',
'nom' => 'Mennegain',
'prenom' => 'Mathieu',
'sexe_id' => 1,
'email' => 'test#test.fr',
'adresse' => '12 rue Jean Rostand',
'cp' => 90000,
'ville' => 'Belfort',
'password' => bcrypt('test123'),
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
'admin' => 0,
]
]);
}
}
My database seeder :
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$this->call(SexesTableSeeder::class);
$this->call(UsersTableSeeder::class);
$this->call(SaisonTableSeeder::class);
$this->call(ProduitTypeSeeder::class);
$this->call(SportsTableSeeder::class);
$this->call(ProduitsTableSeeder::class);
}
}
When i run : php artisan migrate:refresh -seed
I have this error :
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL
: alter table `users` add constraint `users_sexe_id_foreign` foreign key (`
sexe_id`) references `sexes` (`id`))
[PDOException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
The order of migrations is super important. From what you posted you run the users migration first and in that same migration you try to create a users table and alter a table. the other table sexes doesn't exist
($table->foreign('sexe_id')->references('id')->on('sexes');)
so that is why you get a error.
I suggest separating the migrations in order to run users, sexes, alter users or sexes, users and alter in the same migration, but this is not a good way to do things, I mean to mix migrations (create and alter).
Probably there are nothing with id 1 in sexes table and sexe_id => 1 generating this error. In your UsersTableSeeder rather than hardcoding 'sexe_id' => 1 query your sexes table for any row and use that dynamic id.

Resources