I am using Laravel 5.6 and has a multi-auth funcitonality and it works fine. I have user and admin tables in my DB. How can i set a default value on admin table like NAME, EMAIL and PASSWORD? So everytime i run php artisan migrate:refresh i will have the default NAME EMAIL and PASSWORD in admin table? Thank you!
Without a little clarification there are two possible answers to your question. If you are asking about columns in your database tabled having default values this has already been answered but it is simply by chaining the method default on your attribute.
$table->tinyInteger('status')->default('1');
If you are asking about populating a row in your database whenever you migrate refresh. You can use seeders:
Laravel includes a simple method of seeding your database with test
data using seed classes. All seed classes are stored in the
database/seeds directory. Seed classes may have any name you wish, but
probably should follow some sensible convention, such as
UsersTableSeeder, etc. By default, a DatabaseSeeder class is defined
for you. From this class, you may use the call method to run other
seed classes, allowing you to control the seeding order.
<?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
DB::table('users')->insert([
'name' => 'default_name',
'email' => 'default#mail.com',
'password' => 'password',
]);
}
}
And afterwards just call:
php artisan migrate:refresh --seed
Related
I'm using 2 databases in my Laravel application. I have an SQLite DB which is local and a remote MySQL DB. Right now I need to switch env files to connect to each DB when I need to. My question is, is it possible to switch env files so the models which I'm using for both of the DB work on the corresponding DB.
This project is fairly new so if anyone knows a better way to handle this I'm all ears.
You may define several connections on your config/database.php file and access each connection via the connection method on the DB facade:
$sqliteUsers = DB::connection('sqlite')->select(...);
$mysqlUsers = DB::connection('mysql')->select(...);
Check "Using Multiple Database Connections" Section on Laravel docs for more info.
You may use on method on eloquent models:
use App\User;
$sqliteUsers = User::on('sqlite')->get()
$mysqlUsers = User::on('mysql')->get();
You may also specify a connection for an eloquent model statically:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
/**
* The connection name for the model.
*
* #var string
*/
protected $connection = 'sqlite';
}
Check "Database Connection" Section on Laravel docs for more info.
what is database seeding and why we use in laravel i am new in laravel i do not understand why we are using seeding and what is that and seeding use are in laravel relationship why we are using please explain what is that seeding
public function run()
{
DB::table('users')->insert([
'name' =>Ste::random(10),
'email' =>Ste::random(10).'#gmail.com',
'password' =>crypt('secret'),
]);
}
}
what is seeder and why should use this seeder.
Seeding a database is a process in which an initial set of data is provided to a database when it is being installed . It is especially useful when we want to populate the database with data we want to develop in future. When we are building an application we often need the database to be present before we are finishing the module for inserting data, then we can seed the database. Or in simple words seeding is creating dummy datas.
Seeding is not a must or mandatory, but in some case you will need it.
in your code we are seeding the user data with name of random string, email of randomstring#gmail.com,and password of secret.
further reading https://laravel.com/docs/5.8/seeding
DO THE RESEARCH DON'T BE LAZY
I have following sitation (I will describe it as history line):
I setup project witch User model (and users table) with migration file A
After some time i add user_modules table many-to-many and I was force to initialize this array during schama update in migration file B. I do it by
User::chunk(100, function($users) {
foreach ($users as $user) {
$user->userModule()->create();
}
});
After some time i need to update User model and table by add soft-delete (column delete_at) in migration file C and field $dates=['deleted_at'] in User model.
Then I develop system and add more migrations but at some point new developer join to our team and he must build DB schema from scratch so he run php artisan:migrate but he get error in migration file B:
[Illuminate\Database\QueryException (42S22)]
SQLSTATE[42S22]: Column not found: 1054 Unknown column
'users.deleted_at' in 'where clause' (SQL: select * from users
where users.deleted_at is null order by users.id asc limit 100
off set 0)
So the current User model is incompatible witch migration file B
How to deal with that situation?
Where I made mistake and what to do to prevent such situation in future?
This is because of Soft Deletes. When you add the trait SoftDeletes to a model, it will automatically add where users.deleted_at is null to all queries. The best way to get around this is to add withTrashed() to your query in migration B.
To do this, change your query in migration B to look like the following. This should remove the part where it's trying to access the non existent deleted_at column. This migration, after all, is not aware that you want to add soft deletes later on, so accessing all users, including those that are trashed, makes perfect sense.
User::withTrashed()->chunk(100, function($users) {
foreach ($users as $user) {
$user->userModule()->create();
}
});
You could always comment out the SoftDelete trait on the user model before running the migrations also, but that's a temporary fix since you'll need to explain it to all future developers. Also, it can be very handy to run php artisan migrate:fresh sometimes. You don't want to have to remember to comment out the trait each time, so adding withTrashed() seems like the most desirable solution to me.
As a final note, I highly suggest NOT adding seeds to your migrations. Migrations should ONLY be used for schema changes. In cases like this, I would use a console command, or a combination of console commands.
For example, you could make a console command that gets triggered by php artisan check:user-modules. Within this command, you could have the following which will create a user module only if one does not yet exist.
User::chunk(100, function($users) {
foreach ($users as $user) {
if (!$user->userModule()->exists()) {
$user->userModule()->create();
}
}
});
You should be able to run this command at any time since it won't overwrite existing user modules.
Alternative answer: In such situation when we need to generate or transform some data after db schema change - we should NOT use Models (which can independently change in future) but instead use inserts/updates:
DB::table('users')->chunkById(100, function ($users) {
foreach ($users as $user) {
DB::table('user_modules')->insert(
['user_id' => $user->id, 'module_id' => 1]
);
}
});
As it is written in laravel documentation, seeders are designed for data seeding with test data but not for data transformation - so migration files are probably good place to put transformation code (which can generate or change some production data in DB after schema update)
Laravel includes a simple method of seeding your database with test data using seed classes.
Add this to your old migration queries
use Illuminate\Database\Eloquent\SoftDeletingScope;
User::withoutGlobalScope(new SoftDeletingScope())
I am wondering is there a way to make 10-50 rows as default rows that could be added after migration in database?
In case I need to use php artisan migrate:fresh its pain to add simple values over and over again. Like I have Countries table where I need to add over and over again when I run migrate:fresh...
OR
Can I somehow exclude some tables from others that would be affected with command lines
Like inside create_countries_table:
DO_NOT_TOUCH_THIS_TABLE
Thanks
UPDATE:
Without routes etc. Just by migrations
Laravel has a great system about that, all you need to use database seeders.
For exaple you have a users table and you want to make some users.
First create a seeder using make:seeder command
php artisan make:seeder UsersTableSeeder
Then open your UsersTableSeeder and add these lines
public function run()
{
DB::table('users')->insert([
'name' => str_random(10),
'email' => str_random(10).'#gmail.com',
'password' => bcrypt('secret'),
]);
}
Then open your DatabaseSeeder class and add this line
public function run()
{
$this->call(UsersTableSeeder::class);
}
and run db:seed command
php artisan db:seed
For more further check out the seeding on laravel docs
I'm trying to find a optimal way to save and access my paypal credentials on laravel from my Database.
I know it is common to save this kind of data on the .env file or a config file, but I need the user to save his credentials instead of mine.
So what I really need is save the paypal credentials and give the opportunity to personalize their credentials and other data.
There are probably many ways to do this, but the most secure way in my opinion is to use a database. You can use Laravel's Eloquent to talk with your database. It is also a good idea to encrypt the user's PayPal credentials before storing them in your database.
Here is a sample of what I have done in the past to start my database. You will of course have to create the table in your database.
<?php
namespace Application\UserCredentials;
use Illuminate\Database\Eloquent\Model as Eloquent;
class Credentials extends Eloquent
{
protected $table = 'credentials';
protected $fillable = [
'clientID',
'clientSecret',
'user_id'
];
}
Here is an example of what I have used to add this to your database.
<?php
use Credentials;
$userCredentials = Credentials->create([
'clientID' => $clientId,
'clientSecret' => $clientSecret
]);
This should get you started with what you can do with Eloquent in Laravel.