laravel database seeder adding add foreign key id randomly to seeds - php

I am trying to create seeders for testing purposes. I have users that belongs to a room via a room id, these rooms are created via a room seeder, in my users seeder, I create a user and update the room_id attribute like this,
factory(App\User::class, 150)->create([
'host' => false,
'room_id' => App\Room::inRandomOrder()->first()->id
]);
My problem is that all users generated here, all get the same room id, how can a truly get a random room id from the database and use it in my seeder?

I had the same problem with seeding. The problem is that, you are overriding the factory's default model attributes by passing an array of "values". You are passing the value of App\Room::inRandomOrder()->first()->id to the create method. So you would have all users with the same room_id.
To solve this issue, in laravel 8, you can move the 'room_id' => Room::inRandomOrder()->first()->id to your UsersFactory definition:
class UsersFactory {
...
public function definition()
{
return [
'room_id' => Room::inRandomOrder()->first()->id
];
}
...
}
And create users like this,
App\User::factory()->count(150)->create([
'host' => false
]);
In older version of laravel, define your factory as below:
$factory->define(App\User::class, function ($faker) use ($factory) {
return [
'room_id' => Room::inRandomOrder()->first()->id
];
});
And create users like this,
factory(App\User::class, 150)->create([
'host' => false,
]);

Try:
App\Room::all()->random()->id

/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$users = factory(\App\User::class, 150)->create([
'host' => false,
'room_id' => $this->getRandomRoomId()
]);
}
private function getRandomRoomId() {
$room = \App\Room::inRandomOrder()->first();
return $room->id;
}
Try this one. It works for me. Hopefully it works for you.

Try this one. Also, make sure that you have multiple auto incremented room entries in the room table.
$factory->define(App\User::class, function ($faker) use ($factory) {
return [
'host' => false,
'room_id' => $factory->create(App\Room::class)->id
];
});

Related

Laravel exists custom validation rule unable to validate user id with phpunit

I have a validation rule taken from the Laravel Documentation which checks if the given ID belongs to the (Auth) user, however the test is failing as when I dump the session I can see the validation fails for the exists, I get the custom message I set.
I have dumped and died the factory in the test and the given factory does belong to the user so it should validate, but it isn't.
Controller Store Method
$ensureAuthOwnsAuthorId = Rule::exists('authors')->where(function ($query) {
return $query->where('user_id', Auth::id());
});
$request->validate([
'author_id' => ['required', $ensureAuthOwnsAuthorId],
],
[
'author_id.exists' => trans('The author you have selected does not belong to you.'),
]);
PHPUnit Test
/**
* #test
*/
function adding_a_valid_poem()
{
// $this->withoutExceptionHandling();
$user = User::factory()->create();
$response = $this->actingAs($user)->post(route('poems.store'), [
'title' => 'Title',
'author_id' => Author::factory()->create(['name' => 'Author', 'user_id' => $user->id])->id,
'poem' => 'Content',
'published_at' => null,
]);
tap(Poem::first(), function ($poem) use ($response, $user)
{
$response->assertStatus(302);
$response->assertRedirect(route('poems.show', $poem));
$this->assertTrue($poem->user->is($user));
$poem->publish();
$this->assertTrue($poem->isPublished());
$this->assertEquals('Title', $poem->title);
$this->assertEquals('Author', $poem->author->name);
$this->assertEquals('Content', $poem->poem);
});
}
Any assistance would be most appreciated, I'm scratching my head at this. My only guess is that the rule itself is wrong somehow. All values are added to the database so the models are fine.
Thank you so much!
In your Rule::exists(), you need to specify column otherwise laravel takes the field name as column name
Rule::exists('authors', 'id')
Since column was not specified, your code was basically doing
Rule::exists('authors', 'author_id')

Seed multiple custom rows/entries in ModelFactory Laravel

How can I seed multiple rows using ModelFactory in Laravel?
Inside ModelFactory.php I have the following code:
$factory->define(App\User::class, function (Faker $faker) {
static $password;
return [
'name' => 'Admin',
'Description' => 'Administrators have full access to everything.'
];
});
How can I add the following arrays, without using raw expressions?
[
'name' => 'Admin',
'description' => 'Administrators have full access to everything.',
],
[
'name' => 'User',
'description' => 'User have normal access.',
],
Thanks
You can use sequence()
User::factory()->count(2)->sequence(['name' => 'admin'],['name' => 'user'])
->create()
example from laravel documentation
$users = User::factory()
->count(10)
->sequence(fn ($sequence) => ['name' => 'Name '.$sequence->index])
->create();
source https://laravel.com/docs/8.x/database-testing#sequences
Let's say you want to add 100 users in your database.
Create a UserFactory.php in database/factories:
<?php
use Faker\Generator as Faker;
$factory->define(App\User::class, function (Faker $faker) {
return [
'name' => 'Admin',
'Description' => 'Administrators have full access to everything.'
];
});
Then, in database/seeds/DatabaseSeeder.php:
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
factory(App\User::class, 100)->create();
}
}
You can find more details about seeding in the Laravel official documentation.
If you want to have one or two columns to have custom data, you can use each function after creating entries.
$names = ['admin', 'user', 'author', 'subscriber'];
factory(App\User::class, 100)->create()->each(function () use ($names) {
$user->name = $names[array_rand($names)];
$user->save();
});
*Note: Use your own logic inside each function to feed the custom data.
A cleaner way than Raghavendra's proposal (creates one entry per name):
$names = ['admin', 'user', 'author', 'subscriber'];
collect($names)->each(function($name) {
App\Models\User::factory()->create($name);
});

Laravel Factory: Manual Increment of Column

For the following factory definition, the column order needs to be sequential. There is already a column id that is auto-incremented. The first row's order should start at 1 and each additional row's order should be the next number (1,2,3, etc.)
$factory->define(App\AliasCommand::class, function (Faker\Generator $faker) {
return [
'user_id' => App\User::inRandomOrder()->first()->id,
'command' => $faker->word,
'content' => $faker->sentence,
'order' => (App\AliasCommand::count()) ?
App\AliasCommand::orderBy('order', 'desc')->first()->order + 1 : 1
];
});
It should be setting the order column to be 1 more than the previous row, however, it results in all rows being assigned 1.
Here's something that might work.
$factory->define(App\AliasCommand::class, function (Faker\Generator $faker) {
static $order = 1;
return [
'user_id' => App\User::inRandomOrder()->first()->id,
'command' => $faker->word,
'content' => $faker->sentence,
'order' => $order++
];
});
It just keeps a counter internal to that function.
Update:
Laravel 8 introduced new factory classes so this request becomes:
class AliasCommandFactory extends Factory {
private static $order = 1;
protected $model = AliasCommand::class;
public function definition() {
$faker = $this->faker;
return [
'user_id' => User::inRandomOrder()->first()->id,
'command' => $faker->word,
'content' => $faker->sentence,
'order' => self::$order++
];
}
}
The answer by #apokryfos is a good solution if you're sure the factory model generations will only be run in sequential order and you're not concerned with pre-existing data.
However, this can result in incorrect order values if, for example, you want to generate models to be inserted into your test database, where some records already exist.
Using a closure for the column value, we can better automate the sequential order.
$factory->define(App\AliasCommand::class, function (Faker\Generator $faker) {
return [
'user_id' => App\User::inRandomOrder()->first()->id,
'command' => $faker->word,
'content' => $faker->sentence,
'order' => function() {
$max = App\AliasCommand::max('order'); // returns 0 if no records exist.
return $max+1;
}
];
});
You almost had it right in your example, the problem is that you were running the order value execution at the time of defining the factory rather than the above code, which executes at the time the individual model is generated.
By the same principle, you should also enclose the user_id code in a closure, otherwise all of your factory generated models will have the same user ID.
To achieve true autoIncrement rather use this approach:
$__count = App\AliasCommand::count();
$__lastid = $__count ? App\AliasCommand::orderBy('order', 'desc')->first()->id : 0 ;
$factory->define(App\AliasCommand::class,
function(Faker\Generator $faker) use($__lastid){
return [
'user_id' => App\User::inRandomOrder()->first()->id,
'command' => $faker->word,
'content' => $faker->sentence,
'order' => $faker->unique()->numberBetween($min=$__lastid+1, $max=$__lastid+25),
/* +25 (for example here) is the number of records you want to insert
per run.
You can set this value in a config file and get it from there
for both Seeder and Factory ( i.e here ).
*/
];
});
In Laravel 9 (and possibly some earlier versions?), there's a pretty clean way to make this happen when you're creating models (from the docs):
$users = User::factory()
->count(10)
->sequence(fn ($sequence) => ['order' => $sequence->index])
->create();
If you'd like to start with 1 instead of 0:
$users = User::factory()
->count(10)
->sequence(fn ($sequence) => ['order' => $sequence->index + 1])
->create();
The solution also solves already data on table conditions:
class UserFactory extends Factory
{
/**
* #var string
*/
protected $model = User::class;
/**
* #var int
*/
protected static int $id = 0;
/**
* #return array
*/
public function definition()
{
if ( self::$id == 0 ) {
self::$id = User::query()->max("id") ?? 0;
// Initialize the id from database if exists.
// If conditions is necessary otherwise it would return same max id.
}
self::$id++;
return [
"id" => self::$id,
"email" => $this->faker->email,
];
}
}

Laravel Eloquent Modal - First Row?

Inside od a Seeder File I tried to get the first record of my User-Model.
However I can't seem to find the correct way.
I want to fetch the first user, and get its id to use it in user_id (foreign key).
This is not working:
class TerminalsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$user = User::findOrFail(1)->first();
DB::table('terminals')->delete();
Terminal::create([
'serial' => 'R-123-548-753',
'state' => 1,
'user_id' => $user->id
]);
}
}
It fails because I said "1", but it requires one parameter, my first row in user doesn't have an id of 1, but I don't want to hardcode this.
Simple solution is to use the firstOrFail
$user = User::firstOrFail(); //it will return the first record from the top
Terminal::create([
'serial' => 'R-123-548-753',
'state' => 1,
'user_id' => $user->id'
])
You have to check first user found or not
$user = User::first(); // returns the first record found in the database. If no matching model exist, it returns null
if($user)
Terminal::create([
'serial' => 'R-123-548-753',
'state' => 1,
'user_id' => $user->id
]);
}
If user found then it will create new record in terminal.

CakePHP 3: hasOne association not getting saved / created

Cake PHP Version: 3.1.5
I have a problem with saving a hasOne association, which works fine on one table but not with a second.
Ticketsand Cashdrafts are related to Cashpositions in a belongsTo relations. Cashpositions holds two FK for their id. So when a new cashposition is auto-created it holds either a ticket_id or a cashdraft_id. The second FK will be null.
The thing is, that the Tickets-Cashpositions saving is working fine, so everytime a ticket is created a related cashposition is created. But it is not working with Cashdrafts-Cashpositions. I don't understand why, because the setup and relations are exactly the same.
Here is the setup:
class CashpositionsTable extends Table
{
public function initialize(array $config)
{
$this->belongsTo('Tickets', [
'foreignKey' => 'ticket_id'
]);
$this->belongsTo('Cashdrafts', [
'foreignKey' => 'cashdraft_id'
]);
}
}
class TicketsTable extends Table
{
public function initialize(array $config)
{
$this->hasOne('Cashpositions', [
'foreignKey' => 'ticket_id'
]);
}
}
class CashdraftsTable extends Table
{
public function initialize(array $config)
{
$this->hasOne('Cashpositions', [
'foreignKey' => 'cashdraft_id'
]);
}
}
And then in the controllers add() functions:
class TicketsController extends AppController
{
public function add($memberId = null)
{
$ticket = $this->Tickets->newEntity();
if ($this->request->is('post')) {
$ticket = $this->Tickets->patchEntity($ticket, $this->request->data, [
// working fine: creates new cashposition for this ticket
'associated' => ['Cashpositions']
]);
if ($this->Tickets->save($ticket)) {
$this->Flash->success(__('ticket saved'));
return $this->redirect(['action' => 'view', $ticket->$id]);
} else {
$this->Flash->error(__('ticket could not be saved'));
}
}
class CashdraftsController extends AppController
{
public function add()
{
$cashdraft = $this->Cashdrafts->newEntity();
if ($this->request->is('post')) {
$cashdraft = $this->Cashdrafts->patchEntity($cashdraft, $this->request->data,[
// fail: no associated record created
'associated' => ['Cashpositions']
]);
if ($this->Cashdrafts->save($cashdraft)) {
$this->Flash->success(__('cashdraft saved.'));
return $this->redirect(['action' => 'view', $cashdraft->id]);
} else {
$this->Flash->error(__('cashdraft could not be saved'));
}
}
}
I debugged the $ticket and $cashdraft. But I cannot say I understand the output because:
The array for the ticket will show every related data but no cashposition, although a new record for it was created successfully...
And the array for the new cashdraft where the related cashposition is NOT created will look like this and say "null" for it:
object(App\Model\Entity\Cashdraft) {
'id' => (int) 10,
'amount' => (float) -7,
'created' => object(Cake\I18n\Time) {
'time' => '2015-12-13T20:03:54+0000',
'timezone' => 'UTC',
'fixedNowTime' => false
},
'modified' => object(Cake\I18n\Time) {
'time' => '2015-12-13T20:03:54+0000',
'timezone' => 'UTC',
'fixedNowTime' => false
},
'cashposition' => null, // this part not even showing up for a "ticket" in the debug
'[new]' => false,
'[accessible]' => [
'*' => true
],
'[dirty]' => [],
'[original]' => [],
'[virtual]' => [],
'[errors]' => [],
'[repository]' => 'Cashdrafts'
}
In the SQL in DebugKit I can see that for the ticket an INSERT into the related cashpositions table is done. But for cashdrafts there is no INSERT done into the related table. So obviously Cake does not even try to create the associated record.
I'm really out of ideas now! In the database itself both FKs are set up exactly the same, names are correct etc.
Does anybody have an idea what the problem could be or where I could further search for the cause of the second association not working? Thanks!
Ok, so after searching for a million hours I finally realized, that the problem was not with the Model or Controller like I thought. It was (just) the view and the request data not being complete.
Somehow I thought Cake would magically add the entity for the association if non exists even if there is no input for it ;)
In the tickets table for which the saving worked I had an empty input field for a column in Cashpositions that does not even exist anymore and I just hadn't deleted it yet, but it did the trick (don't ask me why).
To fix it now I just put in a hidden input field for the association cashposition.ticket_id and cashposition.cashdraft_id in the add.ctp view for both tables that stays empty. Now the request data contains the array for the association and auto creates a new cashposition with the matching FK every time a new ticket or cashdraft is added.
<!-- Cashdrafts/add.ctp -->
<?php echo $this->Form->input(
'cashposition.cashdraft_id', [
'label' => false,
'type' => 'hidden'
]) ?>
Since I'm just a beginner with this I don't know if this is the best way to go, but it works (finally...)

Categories