escaping comma for faker on lumen seeder - php

I'm learning to do some simple migration and seeding on lumen using factory and faker to mysql database, below are my codes :
PostSeeder.php
use Illuminate\Database\Seeder;
class PostSeeder extends Seeder
{
public function run()
{
factory(App\Models\Post::class, 40)->create();
}
}
and on the factory PostFactory.php
$factory->define(Post::class, function (Faker $faker) {
return [
'post_id' => Str::uuid(),
'title' => $faker->sentence(3),
'content' => $faker->realText(200),
'user_id' => Str::uuid(),
'created_at' => $faker->dateTimeBetween('-1 years', 'now')->format('Y-m-d H:i:s'),
'created_by' => Str::uuid(),
'app' => NULL
];
});
when I tried to run the seeder got error like this :
SQLSTATE[22001]: String data, right truncated: 1406 Data too long for
column 'user_id' at row 1 (SQL: insert into 'posts' ('post_id', 'title',
'content', 'user_id', 'created_at', 'created_by', 'app') values
(c1460ae8-e472-4439-aad8-af3aaf090268, Assumenda
ipsa corrupti., King triumphantly, pointing to the shore, and then
treading on her spectacles, and began picking them up again as quickly
as she could. The next thing was snorting like a wild beast,
screamed 'Off.))
I'm not sure, but looks like on faker realText comma is not being escaped on the query, is there anything I need to add on the factory to escape the faker, or need to do something on the database?
I'm using mysql 14.14 on ubuntu 18.04 and lumen 7.x
on posts table the content type is text

Related

Error : "Trying to get property 'id' of non-object" with Foreign keys on Laravel8

I want to write a correct PostFactory for seed my DB with Laravel8
I follow the documentation on Laravel8 for make my Factory for seed my database
https://laravel.com/docs/8.x/seeding#using-model-factories
I have 3 Models :
Category.php
Post.php
User.php
I can seed my DB when i use this command :
php artisan db:seed --class=UserSeeder
php artisan db:seed --class=CategorySeeder
But i can't seed :
php artisan db:seed --class=PostSeeder
php artisan db:seed for seed all DB with one command
My PostSeeder :
class PostSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
\App\Models\Post::factory(50)->create();
}
}
My PostFactory :
public function definition()
{
return [
'title' => $this->faker->sentence(rand(5, 10)),
'content' => $this->faker->sentences(50, true),
'image' => 'https://via.placeholder.com/350/65' . rand(1, 100),
'created_at' => now(),
'updated_at' => now(),
'category_id' => Category::inRandomOrder()->first()->id,
'users_id' => User::inRandomOrder()->first()->id,
];
}
My PostFactory does'nt want to take my seed
I encounter this error :
PS C:\Users\Chris\Desktop\Laravel_Projects\Blog> php artisan db:seed
ErrorException
Trying to get property 'id' of non-object
at C:\Users\Chris\Desktop\Laravel_Projects\Blog\database\factories\
28▕ 'content' => $this->faker->sentences(50, true),
29▕ 'image' => 'https://via.placeholder.com/350/65'
30▕ 'created_at' => now(),
31▕ 'updated_at' => now(),
1 C:\Users\Chris\Desktop\Laravel_Projects\Blog\database\factories\PostFactory.php:32
Illuminate\Foundation\Bootstrap\HandleExceptions::handleError("Trying to get property 'id' of non-object", "C:\Users\Chris\Desktop\Laravel_Projects\Blog\database\factories\PostFactory.php", [])
2 C:\Users\Chris\Desktop\Laravel_Projects\Blog\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Factories\Factory.php:424
Database\Factories\PostFactory::definition()
My problem come with my 2 foreign keys :
I see the other post with this error but i can't debug with a dd();
I don't found how write my definition for my 2 foreign keys
I have try to check() my id but it'same result.
And to seed my posts_table after and before my users_table and catergories_table it's same.
I tried things with the different posts on the subject without success..Any help is appreciated.
Use the random id it is create random id and how many create record so you define in your seeder.this two line add on your post factory. i hope help you.
'category_id' => Category::all()->random()->id,
'users_id' => User::all()->random()->id,

Importer function issue using Maat, Excel and Laravel

I know this may seem like a long shot, but I have no idea why my importer is missing some columns and taking in others.
I have required the latest Maat version and even did a test using their example to a table of mine and it worked like a charm with the exact table I am using now.
However, there were a few things I need to happen on the create, so I ended up changing it to what was suggested here: https://laracasts.com/discuss/channels/laravel/how-to-include-created-at-and-updated-at-with-imported-file (about 5th answer down)
So now I have a controller function that looks like this:
public function importCustomers (Request $request)
{
if($request->file('imported-file'))
{
$path = $request->file('imported-file')->getRealPath();
$data = Excel::load($path, function($reader) {
})->get();
if(!empty($data) && $data->count()){
foreach ($data as $key => $value) {
$user = Auth::user()->id;
Customer::create([
'company_name' => $value->company_name,
'first_name' => $value->first_name,
'last_name' => $value->last_name,
'account_type' => $value->account_type,
'shipping_address_1' => $value->shipping_address_1,
'shipping_address_2' => $value->shipping_address_2,
'shipping_city' => $value->shipping_city,
'shipping_state' => $value->shipping_state,
'shipping_zipcode' => $value->shipping_zipcode,
'billing_address_1' => $value->billing_address_1,
'billing_address_2' => $value->billing_address_2,
'billing_city' => $value->billing_city,
'billing_state' => $value->billing_state,
'billing_zipcode' => $value->billing_zipcode,
'primary_phone' => $value->primary_phone,
'mobile_phone' => $value->mobile_phone,
'primary_fax' => $value->primary_fax,
'old_account_number' => $value->old_account_number,
'website' => $value->website,
'customer_name' => $value->customer_name,
'origin' => $value->origin,
'primary_email' => $value->primary_email,
'created_by' => $user,
'carrier' => $value->carrier,
'notes' => $value->notes
]);
}
}
}
Session::flash('flash_message','Database successfully imported!');
return back();
}
and this is the top of my controller up until the end of $fillable:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Customer;
use App\Shipment;
use App\Equipment;
use Validator;
use Response;
use App\User;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Auth;
use DB;
use Storage;
use Illuminate\Http\File;
use Excel;
class CustomerController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
protected $rules =
[
// 'originName' => 'required|min:2|max:32|regex:/^[a-z ,.\'-]+$/i',
'account_type' => 'required'
];
protected $fillable =
[
'company_name',
'first_name',
'last_name',
'account_type',
'shipping_address_1',
'shipping_address_2',
'shipping_city',
'shipping_state',
'shipping_zipcode',
'billing_address_1',
'billing_address_2',
'billing_city',
'billing_state',
'billing_zipcode',
'primary_phone',
'mobile_phone',
'primary_fax',
'old_account_number',
'website',
'customer_name',
'origin',
'primary_email',
'created_by',
'carrier',
'notes'
];
I get the following error if I try to post the import:
SQLSTATE[HY000]: General error: 1364 Field 'created_by' doesn't have a default value (SQL: insert into `customers` (`company_name`, `first_name`, `last_name`, `account_type`, `shipping_city`, `shipping_state`, `billing_city`, `billing_state`, `primary_phone`, `primary_fax`, `customer_name`, `origin`, `primary_email`, `updated_at`, `created_at`) values (BULLET LINE, , , 1, OAK CREEK, WI, OAK CREEK, WI, , , BULLET LINE, 0, , 2017-12-20 19:15:47, 2017-12-20 19:15:47))
As you see, "created_by" is in fact a field in my MySQL table, by it's not even a field that is being passed or anything like that. Even though you can see it's not from my csv, rather the value comes from $auth::user()->id but there are missing fields that I know for a fact are in my excel sheet (and didn't have a problem being imported when I tried out using the document of just importing everything), and you can see them in my function, and they are fillable so I'm not sure what's going on.
The current missing fields are:
shipping_address_1
shipping_address_2
shipping_zipcode
billing_address_1
billing_address_2
billing_zipcode
mobile_phone
old_account_number
website
carrier
notes
Does anyone have any suggestions?
You have to move $fillable variable to Customer Model. It is in the wrong file, it is not going to work in the Controller file. This is the reason why it is missing fields. Probably $fillable variable in Model file is missing these fiels.
Ref: https://laravel.com/docs/5.5/eloquent#mass-assignment

How to seed a date field in Laravel 5.3?

I've managed to set up a decent amount of seeding for data that needs to be in the database at launch. Everything was easy and working well until I needed to seed a DATE field with a default date.
I've tried the following...
DatabaseSeeder.php
class SettingsTableSeeder extends Seeder {
public function run()
{
Setting::create([
'name' => 'Start Date',
'date' => '2000-01-01'
]);
}
}
In my model I've been told adding this should fix it, but it didn't.
Setting.php
protected $dates = [
'created_at',
'updated_at',
'date'
];
Everytime I go to run the seeder it throws the error:
[InvalidArgumentException]
The separation symbol could not be found
Unexpected data found.
Trailing data
If I remove the quotes around the date it changes to..
[InvalidArgumentException]
The separation symbol could not be found
Data missing
Any idea how one goes about seeding a default value for a DATE database field?
If date is in the $dates array, insert Carbon instance instead of a string:
Setting::create([
'name' => 'Start Date',
'date' => Carbon::parse('2000-01-01')
]);
You'll need to make sure that Carbon is available to use at the top of the file:
use Carbon\Carbon;
It is auto-loaded by Laravel/Composer.
Just try inserting the date using Carbon like,
class SettingsTableSeeder extends Seeder {
public function run(){
Setting::create([
'name' => 'Start Date',
'date' => \Carbon\Carbon::createFromDate(2000,01,01)->toDateTimeString()
]);
}
}
The given answers by Alexey Mezenin and Jaymin Panchal both still resulted in the trailing data error being thrown.
What ended up working for me was including...
use Carbon\Carbon;
at the top of the DatabaseSeeder.php file.
Then changing my Setting::create to...
DB::table('settings')->insert([
'name' => 'Start Date',
'date' => Carbon::create('2000', '01', '01')
]);
for some reason I can't use Carbon with the standard Model::create method while seeding, but it works for DB::table('table')->insert.
$dates= [
['name' =>'Start Date'],
];
foreach ($dates as $date) {
Setting::create($date);
}

Yii2 TimestampBehavior not working correctly

I am using most recent version of Yii framework (2.0.6). I have table Post with PostModel and in my model I need to set correctly created_at and updated_at properties. As soon as I create new Post, both values are set to current timestamp, but when I update this post, it will also update both attributes in table to current time, even though only updated_at should be updated and created_at should remain the same.
use yii\behaviors\TimestampBehavior;
public function behaviors() {
return [
[
'class' => TimestampBehavior::className(),
],
[
'class' => SluggableBehavior::className(),
'attribute' => 'name',
],
];
}
This is the other version, but still not working:
public function behaviors()
{
return [
'timestamp' => [
'class' => TimestampBehavior::className(),
'attributes' => [
\yii\db\ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
\yii\db\ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
],
],
[
'class' => SluggableBehavior::className(),
'attribute' => 'title',
],
];
}
I am also using MariaDB database. If you could help me, what is going on with my code, I will appreciate it very much.
First of all, the second snippet is not correct, because attributes array is not designed to be set by user. It's kind of inner logic, you only need to set createdAtAttribute and updatedAtAttribute properties. Accordingly they are named created_at and updated_at by default, so if your naming is the same, you can just omit this declaration as you did in first snippet.
It's better to explicitly add this too:
use yii\db\Expression;
...
`value` => new Expression('NOW()'),
To prevent changing created_at column value during update, you can add DEFAULT CURRENT_TIMESTAMP.
Here is snippet from migration:
use yii\db\Schema;
...
'created_at' => Schema::TYPE_TIMESTAMP . ' NOT NULL DEFAULT CURRENT_TIMESTAMP',
'updated_at' => Schema::TYPE_TIMESTAMP . ' NOT NULL',
See this related question for more details.
It's for MySQL, but I guess for MariaDB is the same or very similar.

Laravel 5.1 Localize Factory Seeder

I implemented a new factory to generate random data. But I want to have this random data in the format of de_DE. So usually I create a faker object first, but this is not the case in Laravel 5.1 with the new ModelFactory class. How do I localize this then?
$factory->define(App\Models\AED::class, function($faker) {
return [
'owner' => $faker->company,
'street' => $faker->streetAddress,
'latitude' => $faker->latitude,
'longitude' => $faker->longitude
];
});
In order to change the default locale used by Faker, the easiest way is to simply override the FakerGenerator binding with your own concrete implementation:
// AppServiceProvider.php
$this->app->singleton(FakerGenerator::class, function () {
return FakerFactory::create('nl_NL');
});
On top of your AppServiceProvider.php file add the following lines:
use Faker\Generator as FakerGenerator;
use Faker\Factory as FakerFactory;
For example, the above code will mean all Faker instances are created using the nl_NL provider, thus creating Dutch faker data.
Remember: this has to happen after the DatabaseServiceProvider has been executed, so make sure to put your own AppServiceProvider after all of the Laravel ServiceProviders in your config.php array.
Try
$factory->define(App\Models\AED::class, function($faker) {
$faker->locale = "YOUR_LOCALE";
...
});
Add this either at the top of your ModelFactory.php or in your AppServiceProvider::register() method:
$this->app->singleton(\Faker\Generator::class, function () {
return \Faker\Factory::create('de_DE');
});
You must add Providers eg.
$factory->define(Mylead\Models\UserDetails::class, function($faker) {
$faker->addProvider(new Faker\Provider\pl_PL\Person($faker));
$faker->addProvider(new Faker\Provider\pl_PL\Payment($faker));
return [
'name' => $faker->name,
'surname' => $faker->lastname,
'street' => $faker->streetName,
'city' => $faker->city,
'post_code' => $faker->pesel,
'pesel' => $faker->pesel,
'paypal' => $faker->email,
'bank_name' => $faker->bank,
'bank_account' => $faker->bankAccountNumber,
'created_at' => $faker->dateTime
];
});
For now You can't set manualy Faker locale. It should be changed on Laravel Core

Categories