I have this software and I need to create new institutions (like kindergardens). How to migrate into that new database?
if ($newDb) {
Config::set('database.connections.th', [
'driver' => 'mysql',
'host' => 'localhost',
'port' => '3306',
'database' => 'kindergarden'.$institutionId,
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'timezone' => '+00:00',
'strict' => false,
]);
return \Illuminate\Support\Facades\Artisan::call('migrate');
}
And migrations are like
public function up()
{
Schema::create('students', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('first_name', 100);
$table->string('last_name', 100);
$table->tinyInteger('gender');
$table->date('date_of_birth');
$table->string('address', 150);
$table->string('phone_number', 20);
$table->string('email', 100);
$table->unsignedTinyInteger('status')->default(1);
$table->timestamps();
$table->softDeletes();
});
}
Set the non default database connection in your table migration
Schema::connection('th')->create('students', function (Blueprint $table)
This will inform artisan to migrate this table to the specified database in your configuration
From the Docs
Database Connection & Table Options
If you want to perform a schema operation on a database connection that is not your default connection, use the connection method:
Schema::connection('foo')->create('users', function (Blueprint $table) {
$table->bigIncrements('id');
});
Related
This question already has answers here:
How to create a laravel hashed password
(16 answers)
Closed last year.
Can i create the first record in the database via migration, where in the passwordcolumn it is already bcrypted
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email');
$table->string('level');
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
User::firstOrCreate([
'name' => 'admin',
'email' => 'admin#app.com',
'level' => 'Administrator',
'password' => 'password'
]);
}
the code is working but the password is not encrypted, any suggestion ?
Save password in this way:
'password' => Hash::make('password');
Or you can use this way:
'password' => bcrypt('password');
To follow the pattern, it would be nice to create the first record in the database in a seed and not in the migration.
public function up()
{
Schema::create('settings', function (Blueprint $table) {
$table->id();
$table->string('name', 40)->unique();
$table->json('value');
$table->timestamps();
});
//seeder to insert FTP settings
DB::table("settings")->insert([
'name' => 'FTP_SETTINGS',
'value' => ['host' => '192.168.5.190', 'username'=> 'Alessandro', 'password' => 'Alessandro', 'port' => '21']
]);
}
I'm doing this migration with a seeder after that (I've also put it into the seeder section but has the same issue) but i get the ErrorException Array to string conversion.
Probably is something with the value propriety but I cannot understand what I'm doing wrong..many thanks for your help.
You are trying to insert array values into json filed.
Try instead:
DB::table("settings")->insert([
'name' => 'FTP_SETTINGS',
'value' => json_encode(['host' => '192.168.5.190', 'username'=> 'Alessandro', 'password' => 'Alessandro', 'port' => '21'])
]);
I define a new guard "Admin" to have a multi Auth System User and admin in my project . web guard allows login.But admin guard does not allow login
when I try to login into Admin ,it gives
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'last_sign_in_at' in 'field list' (SQL: update `admins` set `updated_at` = 2020-09-27 12:49:24, `last_sign_in_at` = 2020-09-27 12:49:24, `current_sign_in_at` = 2020-09-27 12:49:24 where `id` = 1)
My users table
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('user_type');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->boolean('status')->default(0);
$table->timestamp('last_sign_in_at')->nullable();
$table->timestamp('current_sign_in_at')->nullable();
$table->string('user_click');
$table->timestamp('user_click_time')->nullable();
$table->rememberToken();
$table->timestamps();
});
}
My admin table
public function up()
{
Schema::create('admins', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('user_type');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->boolean('status');
$table->rememberToken();
$table->timestamps();
});
}
auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
//admin guard
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
'admins' => [
'provider' => 'admins',
'table' => 'password_resets',
'expire' => 60,
],
],
My Middleware CheckRole
public function handle($request, Closure $next)
{
if (!Auth::guard('admin')->check()){
return redirect('admin/login');
}
return $next($request);
}
My Admin.php Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
//guard
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
//guard End
class Admin extends Authenticatable
{
use Notifiable;
protected $guard ='admin';
protected $hidden = [
'password', 'remember_token',
];
protected $guarded=[];
protected $casts = [
'email_verified_at' => 'datetime',
];
}
My AdminController
public function adminLogin(Request $request){
if ($request->ismethod('post')) {
$data = $request->input();
if ( Auth::guard('admin')->attempt(['email' => $data['email'], 'password' => $data['password'],
'user_type'=>'admin', 'status' => '1'])){
return view('admin.dashboard');
}
else {
return back()->with('error',' Invalid UserName Or Password');
}
}
}
When I tried to login into Admin, It gives error. Any solution ps !
It seems like you have an event listener listening for Auth's LoginEvent and it is setting the last_sign_in_at field on the Model and saving it. Since you are using different models for Authentication it will end up trying to do this on what ever Model is in that event; in this case the Admin model.
You will need to add this field to your admin table, or you will have to check in the listener which Model the event is holding and decide whether to update this field depending on what type that model is.
I have 2 tables named Users and Users_meta. Both are sharing One-To-One relationship. I would like to insert dummy data with the help of seeding. I am able to do that, the only thing that is driving me crazy is that, I am unable to establish relationship between users and users_meta table with user_id as foreign key. I tried few ways but that either creates duplicate entires with same user_id or keeps repeating the same user_id.
What exactly I would like is; when creating for example 100 records, after first user record insertion, it should take the same user's user_ID, add it to users_meta table's user_id field and repeat the insertion till 100 fake records.
Any help on this would be greatly appreciated
Code in : UserFactory.php
$factory->define(App\User::class, function (Faker $faker) {
static $password;
return [
'username' => $faker->userName,
'email' => $faker->unique()->safeEmail,
'password' => $password ?: $password = bcrypt('secret'),
'referral_code' => str_random(10),
'referred_by_code' => str_random(10),
'role' => $faker->randomElement(['administrator', 'user', 'volunteer']),
'remember_token' => str_random(10),
]; });
Code in : UsersMetaFactory.php
$factory->define(App\Usersmeta::class, function (Faker $faker) {
return [
'user_id' => $faker->randomElement(\App\User::pluck('id')->toArray()),
'first_name' => $faker->firstname,
'last_name' => $faker->lastname,
'gender' => $faker->randomElement(['male', 'female']),
'date_of_birth' => $faker->dateTimeThisCentury->format('Y-m-d'),
'address' => $faker->address,
'city' => $faker->city,
'state' => $faker->state,
'zip_code' => $faker->postcode,
'country' => $faker->country,
'cell_phone' => $faker->e164PhoneNumber,
'bitcoin_address' => str_random(16),
'monero_address' => str_random(16),
'security_question' => $faker->realText($maxNbChars = 20, $indexSize = 2),
'security_answer' => $faker->realText($maxNbChars = 40, $indexSize = 2),
'is_founder' => $faker->boolean($chanceOfGettingTrue = 50),
'status' => $faker->randomElement(['active', 'inactive']),
'terms' => $faker->boolean
]; });
The randomElement() method gives me random id which violates one to one relationship principal and my app breaks down. I would like it should fetch id from users table and pass the same id as user_id to users_meta table and continue generating fake records.
CreateUsersTable migration class
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('username')->unique();
$table->string('email')->unique();
$table->string('password');
$table->string('referral_code')->unique();
$table->string('referred_by_code');
$table->enum('role', ['administrator', 'user', 'volunteer'])->nullable();
$table->rememberToken();
$table->timestamps();
});
}
CreateUsersMetaTable migration class
public function up()
{
Schema::create('users_meta', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->string('first_name');
$table->string('last_name');
$table->enum('gender', ['male', 'female'])->nullable();
$table->string('date_of_birth')->nullable();
$table->string('address')->nullable();
$table->string('city')->nullable();
$table->string('state')->nullable();
$table->string('zip_code')->nullable();
$table->string('country');
$table->string('cell_phone');
$table->string('bitcoin_address')->nullable();
$table->string('monero_address')->nullable();
$table->string('security_question');
$table->string('security_answer');
$table->string('is_founder')->nullable();
$table->enum('status', ['active', 'inactive'])->nullable();
$table->string('terms');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('users_meta');
Schema::enableForeignKeyConstraints();
}
You should remove this line:
'user_id' => $faker->randomElement(\App\User::pluck('id')->toArray()),
And use relationship when creating a new model. Here's a modified example from the docs:
factory(App\User::class, 50)->create()->each(function ($u) {
$u->usersmeta()->save(factory(App\Usersmeta::class)->make());
});
So I have a lot of migration files from a previous database setup. I'd like to apply these files to a new database. For example, if I were starting from scratch I would do something like this:
php artisan make:migration create_users_table
and then:
php artisan migrate
for every single migration file. But since I already have all the migration files, is there a way to skip all of the make:migration part and get it to create the corresponding tables?
I've tried:
php artisan migrate --force
but it doesn't work. What's the right way to do this? This is a clean installation of Laravel 5.5.
I'm getting this error:
This is the schema where the error is happening:
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('username');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamp('created_at');
$table->timestamp('updated_at');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
I am unable to post comments so posting this as an answer.
try $table->timestamps();
Don't write created_at and updated_at separately.
Also try this:-
$table->string('remember_token', 100) -> nullable();
This seems to be the last hope now.
try $table->timestamps() -> nullable();
Set strict to true in my MySQL config (in .env or config/database.php).
'connections' => [
'mysql' => [
'driver' => 'mysql',
'host' => 'localhost',
'database' => env('DB_DATABASE', 'homestead'),
'username' => env('DB_USERNAME', 'homestead'),
'password' => env('DB_PASSWORD', 'secret'),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => true
]
],