I am using Laravel (4.2)
I am working on a project with an authentication system. I need to insert a first user into my users table. I would like to do that directly with a sql command (insert into users....). Because this first user can't be created with the traditional laravel methods.
This first user will be identified with the auth::attempts method, after being inserted into the table.
How do I insert this user into mysql table?
something like?
insert into users (login, password) values ('admin', 'crypted password which can be later identified with laravel')
We can insert the record using the DB facade with insert method. The syntax of insert method is as shown in the following table. Run an insert statement against the database.
After configuring the database, we can retrieve the records using the DB facade with select method. The syntax of select method is as shown in the following table. Run a select statement against the database.
I'm doing it this way:
creating seeder with artisan:
php artisan make:seeder UsersTableSeeder
then you open the file and you enter users:
use Illuminate\Database\Seeder; class UsersTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('users')->insert([ 'name' => 'User1', 'email' => '[email protected]', 'password' => bcrypt('password'), ]); DB::table('users')->insert([ 'name' => 'user2', 'email' => '[email protected]', 'password' => bcrypt('password'), ]); } }
If you want to generate random list of users, you can use factories:
use Illuminate\Database\Seeder; class UsersTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { factory(App\User::class, 50)->create(); /* or you can add also another table that is dependent on user_id:*/ /*factory(App\User::class, 50)->create()->each(function($u) { $userId = $u->id; DB::table('posts')->insert([ 'body' => str_random(100), 'user_id' => $userId, ]); });*/ } }
Then in the file app/database/seeds/DatabaseSeeder.php uncomment or add in run function a line:
$this->call(UsersTableSeeder::class);
it will look like this:
use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $this->call(UsersTableSeeder::class); } }
At the end you run:
php artisan db:seed
or
php artisan db:seed --class=UsersTableSeeder
I hope will help someone. PS: this was done on Laravel 5.3
For password, open root of your project in terminal.
Then run php artisan tinker;
Then echo Hash::make('password');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With