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
Related
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 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
I'm trying to write some Laravel factories so that we can seed all tables upfront and also use them for tests.
I'm not very experienced with testing and I have some doubts on which premises should factories be built.
Let's use this simple example, 2 tables:
users
notes
Notes have a user_id field with a FK.
Should I make the notes factory to be able to create users (calling users factory) or expect that in any test that I try to create notes I
have already created users that can be associated with the notes?
Please give some practical example if you may.
Relationship while seeding can be done. Try this code in your NoteFactory.
'user_id' => function(){
return App\User::all()->random();
}
Note that your UserFactory should run first and then NoteFactory.
Simple question here:
In laravel 5.3 how would I pull the comments from a database table? Is there a clean way of doing it using some of the out-of-the-box features that laravel provides??
Thank you in advance.
Laravel 5.2-5.3, as far as I know, comes with a built-in package called doctrine that allows you to interact with a lot more within a database and it's tables than eloquent. I believe the framework members will eventually add more to the system so you can make more dynamic use of a DB and tables etc.
For the time being this is how I implement accessing the structure (comments included) of a database table:
$settings = SomeModel::where($items_match)->get(); //Making use of Eloquent
$columns = DB::connection('database_name_here')
->getDoctrineSchemaManager()
->listTableDetails('table_name_here');
foreach ($settings as $key => $value) {
if ($comments[$key] = $columns->getColumn($key)->getComment()) {
}
}
It's fairly clean and get's the job done. The only downside I see is it's a double hit to the DB which I'm thoroughly against, I'm working on a way to combine the 2 implementations in laravel so that it's only 1 query doing both jobs.
Im learning laravel.
My question is about some simple way do display model structure. I have little experience with django and as i remember, structure for each model was placed inside model files.
Yet in laravel, i need to put starting structure inside migration file:
$table->increments('id');
$table->timestamps();
$table->string('name')->default('');
Then if i want to add some new field, i will place this field in next migration file, etc.
So, is there any way to see some kind of summary for model? Maybe some bash command for tinker?
There are a bunch of options for you to choose from.
If you would like to show a summary of a model while you are in tinker, you can call toArray() on an instance of your model.
Ex:
$ php artisan tinker;
>>> $user = new App\User(['email' => 'john#doe.com', 'password' => 'password]);
>>> $user->toArray();
If you are trying to see a summary of a model displayed on your webpage, just var_dump or dd(...) an instance of your model after calling toArray() on it, and you'll get the same result as above, just in your web browser.
If you are looking for a way to show the table structure without creating any Model instances, you can display the table structure in your terminal, the exact command depending on what database you are using.
For example in MySQL you would do something like:
mysql> show COLUMNS from USERS;
It might also be a good idea to get a GUI app, I like Sequel Pro (for Mac).
P.S. I would just add that you should only have separate migrations for adding new fields when you are already in production and can't lose data from your database. While you are still in development and don't care about your data, it is much better to call php artisan migrate:rollback, add the new field to your create migration, and then php artisan migrate again, rather than making tons of new migration files.