Skip to content

Instantly share code, notes, and snippets.

@simondavies
Last active April 24, 2020 13:20
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save simondavies/7ee30b975982595696c4 to your computer and use it in GitHub Desktop.
Save simondavies/7ee30b975982595696c4 to your computer and use it in GitHub Desktop.
<?php
use Illuminate\Database\Seeder;
class PostTagTableSeeder extends Seeder
{
/**
* @var
*/
private $pivotData = [];
/**
* @var
*/
private $totalValues = 9;
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
NameSpaceHere\PostTag::truncate();
//-- lets create some random pivot values
for ($x = 0; $x <= $this->totalValues; $x++) {
//-- get a new pivot value
$new_pivot_value = self::newPivot();
//-- lets add ot to the array for validation
array_push($this->pivotData,$new_pivot_value);
//-- add pivot data to db
DB::table('post_tag')->insert([
'post_id' => $new_pivot_value[0],
'tag_id' => $new_pivot_value[1]
]);
}
}
/**
* Get unique pivot values
*/
function newPivot(){
$pivot_value = self::getData();
$result = self::in_array_r($pivot_value, $this->pivotData);
//-- if its a duplicate then re-run method
if($result) return self::newPivot();
return $pivot_value;
}
/**
* Get the fake data
*/
function getData(){
$faker = Faker\Factory::create();
$postsId = $faker->randomElement(NameSpaceHere\Post::lists('id')->toArray());
$tagsId = $faker->randomElement(NameSpaceHere\Tag::lists('id')->toArray());
return [
(Int)$postsId,
(Int)$tagsId
];
}
/**
* check the new value with currently set picot values already set
*/
function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item)
&& self::in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment