Laravel-Test-Helpers
Laravel-Test-Helpers copied to clipboard
A bit awkward when if set Laravel softDelete to true
The problem I'm having is that if I have a model, say, User which sets protected $softDelete = true. Now when using Factory::create('User'), if I don't specify the override ['deleted_at' => null] then Factory will fill the column automatically, which sort of defies the fact that most of the time, we need deleted_at set to null, otherwise Laravel deems it as trashed already.
To avoid the problem I added 3 lines of code and now the fire method (in Tests\Factory.php) becomes this:
public function fire($class, array $overrides = array())
{
$this->tableName = $this->parseTableName($class);
$this->class = $this->createModel($class);
// First, we dynamically fetch the fields for the table
$columns = $this->getColumns($this->tableName);
// Skip deleted_at and leave it null unless
// we specify it in overrides
if (array_key_exists('deleted_at', $columns)) {
unset($columns['deleted_at']);
}
// Then, we set dummy value on the model.
$this->setColumns($columns);
// Finally, if they specified any overrides, like
// Factory::make('Post', ['title' => null]),
// we'll make those take precedence.
$this->applyOverrides($overrides);
// And then return the new class
return $this->class;
}
This might not be an elegant solution because I havent read through all the source code of Factory helper. Is there any better suggestion as to how to deal with this issue properly?
By the way, I love these laravel helpers, helping me write better tests.
I'm also having this problem. So right now I'm explicitly defining 'deleted_at' => null . Hope this issue gets fixed.
I ran into this as well. And found it'd be better to do
vendor/way/laravel-test-helpers/src/Way/Tests/Factory.php
protected function setColumn($name, $col)
{
- if ($name === 'id') return;
+ if ($name === 'id' || $name == 'deleted_at') return;
$method = $this->getFakeMethodName($name, $col);
if (method_exists($this->dataStore, $method))