Chris Schmitz
Chris Schmitz

Reputation: 20950

Heredoc in Laravel database seed

I'm trying to create a database seed in laravel that uses a heredoc to set an xml structure into a variable and then use that variable as one of the values in the seed:

class CodeTableSeeder extends Seeder {

    public function run()
    {

        DB::table('code')->delete();

        $xml = <<<RawXML
<?xml version="1.0"?>
<fmxmlsnippet type="FMObjectList">
    ...
RawXML;

        Code::create(array('user_id' => 1, 'code' => $xml));
    }
}

When I run the seeder, I get an error message from artisan:

Seeded: UserTableSeeder

  [ErrorException]                 
  Undefined variable: searchValue  

I know that searchValue is within the xml code:

    <Script includeInMenu="True" runFullAccess="False" id="1" name="Perform a Find (searchValue, searchField, LayoutName)">

It seems like the database seeder is reading the xml document as code instead of a heredoc string. Is there a way of preventing the seeder from reading the xml? Is there a better way of including the xml in the seed?

It's not imperative that the xml be included in the seed, but it would be nice to keep an extra step out of the setup process for other devs.

Upvotes: 1

Views: 2034

Answers (1)

Jeff Lambert
Jeff Lambert

Reputation: 24661

Instead of using heredoc, you can instead use nowdoc. From the documentation:

Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc.

See also this answer by deceze which gives a practical example of the difference between the two:

$foo = 'bar';

$here = <<<HERE
    I'm here, $foo!
HERE;

$now = <<<'NOW'
    I'm now, $foo!
NOW;

$here is "I'm here, bar!", while $now is "I'm now, $foo!".

Upvotes: 3

Related Questions