Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel ORM Array to String Conversion

Laravel 5.3, PHP 5.6 Fresh laravel new project, minimal configuration.

I have made a simple migration and model, and am trying to seed data into it via php artisan tinker.

My migration looks like this:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatesFooTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('foo', function (Blueprint $table) {
            $table->increments('id');
            $table->string('foo', 20);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('foo');
    }
} 

When I run php artisan migrate the database populates just fine.

The corresponding model is simple:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Foo extends Model
{
    protected $table = 'foo';

    protected $fillable = ['foo'];

}

I have a ModelFactory as well:

$factory->define(App\Foo::class, function (Faker\Generator $faker) {

    return [
        'foo' => $faker->email,
    ];
});

Tinker does what I think it should do when I try to make a flyer from the factory:

>>> factory('App\Foo')->make();
=> App\Foo {#696
     foo: "[email protected]",

But when I try to hit the database, Eloquent fails to wrap the query values in a string:

>>> $foo = factory('App\Foo')->create();
Illuminate\Database\QueryException with message 'SQLSTATE[22001]: String data, right truncated: 1406 Data too long for column 'foo' at row 1 (SQL: insert into `foo` (`foo`, `updated_at`, `created_at`) values ([email protected], 2016-09-06 23:59:03, 2016-09-06 23:59:03))'

Nothing like this on Google. Any ideas?

(Edited to show the same problem with a much simpler example)

like image 619
Mark Karavan Avatar asked Sep 06 '16 23:09

Mark Karavan


2 Answers

Some of the faker methods return their result as an array, as a default. For example:

$faker->words(3)

would return:

array('porro', 'sed', 'magni')

To return the result as a string you can pass true as the second argument for some methods, as in the previous example using the words method:

$faker->words(3, true)

returns:

"porro sed magni"

As described in the readme:

words($nb = 3, $asText = false)    // array('porro', 'sed', 'magni')
like image 90
haakym Avatar answered Nov 08 '22 10:11

haakym


Solved it. The problem was the faker library. Apparently when you explicitly cast (string)$faker->whatever it fixes the problem.

like image 44
Mark Karavan Avatar answered Nov 08 '22 11:11

Mark Karavan