Ad
How Can I Use A Public Array From My Model In My Seeder To Insert Values In My Table?
I have a Model called Browser which has an array of all the browsers.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Browser extends Model
{
const CHROME = 'chrome';
const FIREFOX = 'firefox';
const OPERA = 'opera';
const SAFARI = 'safari';
const MICROSOFTEDGE = 'microsoft edge';
const INTERNETEXPLORER = 'internet explorer';
public static $types = [self::CHROME, self::FIREFOX, self::OPERA, self::SAFARI, self::MICROSOFTEDGE, self::INTERNETEXPLORER];
}
And I have a Seeder that fills the browsers table.
<?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class BrowserSeeder extends Seeder
{
public function run()
{
DB::table('browsers')->insert(array(
array('name' => 'chrome'),
array('name' => 'firefox'),
array('name' => 'opera'),
array('name' => 'safari'),
array('name' => 'microsoft edge'),
array('name' => 'internet explorer'),
array('name' => 'other'),
));
}
}
Could I use the $types array from my Browser model to inset into the database? Because to insert you need an associative array, and I would like to keep $types as it is. Could I easily convert it to an associative array in my Seeder without needing an array with the keys but with just 1 key?
Ad
Answer
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class BrowserSeeder extends Seeder
{
public function run()
{
$arr = array_map( function( $el ) {
return array('name' => $el );
}, App\Browser::$types );
DB::table('browsers')->insert($arr);
}
}
It's of course not necesary to store in $arr
but this makes it a little more readable I think.
Ad
source: stackoverflow.com
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS - Conditionally Load a Different Page
- → Make a Laravel collection into angular array (octobercms)
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?
- → Validating fileupload(image Dimensions) in Backend Octobercms
- → OctoberCMS Fileupload completely destroys my backend
- → How do I call the value from another backed page form and use it on a component in OctoberCms
Ad