Laravel seeder column json - laravel

I am creating a seeder in laravel, but I have to write 1 column json data, but I could not do it, how can I create a seeder column.
Seeder In seeder there will be "bank name" and "iban" in iban column
Migration
public function up()
{
Schema::create('settings', function (Blueprint $table) {
$table->id();
$table->string('account_type');
$table->string('name');
$table->json('ibans')->nullable();
$table->timestamps();
});
}
Seeder
public function run()
{
DB::table('settings')->insert([
'name' => 'Şirket Ünvanı',
'account_type' => 'settings',
'ibans' => json_decode('"a":1,"b":2',true),
'created_at' => now(),
'updated_at' => now(),
]);
}

It's
public function run()
{
DB::table('settings')->insert([
'name' => 'Şirket Ünvanı',
'account_type' => 'settings',
'ibans' => json_encode(['bankname' => 1, 'iban' => '2', '0' => true]),
'created_at' => now(),
'updated_at' => now(),
]);
}

You can add this json field to your Model (Settings) as casting field (protected $cast). It will be automatically handles json_encode, -decode to an array.
protected $casts = [
'ibans' => 'array'
];
$settings->ibans = $array;
$array = $settings->ibans;
https://laravel.com/docs/8.x/eloquent-mutators#array-and-json-casting

Related

Get the id of the user who created the new user in Laravel

I have a users table and a column supervised_by where I want the id of the user who created the new user. For example: get the id of the admin in supervised_by column of the user the admin creates.
users table
//migration file
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->boolean('verified')->default(false);
$table->timestamp('verified_at')->nullable();
$table->string('password');
$table->string('is_verified');
$table->boolean('active')->nullable();
$table->integer('supervised_by')->references('id')->on('users');
$table->rememberToken();
$table->timestamps();
$table->softDeletes();
});
}
usercontroller
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|max:180',
'email' => 'required|email|unique:users',
'password' => 'required|max:15|min:8',
// 'role' => 'required'
]);
if ($validator->fails()) {
return response()->json([
'validation_errors' => $validator->messages(),
]);
}
else
{
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => $request->password,
'verified' => false,
'role' => $request->role
]);
return response()->json([
'status' => 200,
'code' => 'register',
'message' => 'Registered successfully! You\'ll be able to log in once you are approved.',
'data' => null,
'error' => null,
]);
}
}
You can use auth()->user()->id to get who created the user.
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => $request->password,
'verified' => false,
'role' => $request->role,
'supervised_by' => auth()->user()->id,
]);
You can read the documentation about it from here
(If i understood correctly), the admin who creates the new users is always logged in, so you can track the admin id with following line:
$admin_id = Auth::user()->id;
or,
$admin_id = Auth::id();
Also, dont forget to:
use Illuminate\Support\Facades\Auth;

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null?

I got this error when try to seed database.
Laravel 7.
BlogPost Model
class BlogPost extends Model
{
protected $fillable = [
'title',
'slug',
'user_id',
'category_id',
'excerpt',
'content_raw',
'content_html',
'is_published',
'published_at',
'updated_at',
'created_at',
];
public function category()
{
return $this->belongsTo(BlogCategory::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
}
User model
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
User migration
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
BlogPost migration
Schema::create('blog_posts', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('category_id');
$table->foreignId('user_id')->constrained();
$table->string('title');
$table->string('slug')->unique();
$table->text('excerpt')->nullable();
$table->text('content_raw');
$table->text('content_html');
$table->boolean('is_published')->default(false)->index();
$table->timestamp('published_at')->nullable();
$table->foreign('category_id')->references('id')->on('blog_categories');
$table->timestamps();
});
User seeder
class UserTableSeeder extends Seeder
{
public function run()
{
$users = [
[
'name' => 'Author',
'email' => 'seriiburduja#mail.ru',
'password' => bcrypt('some1234')
],
[
'name' => 'Admin',
'email' => 'seriiburduja#gmail.com',
'password' => bcrypt('some1234')
]
];
DB::table('users')->insert($users);
}
}
BlogPost Factory
$factory->define(BlogPost::class, function (Faker $faker) {
$title = $faker->sentence(rand(3, 8), true);
$text = $faker->realText(rand(1000, 4000));
$isPublished = rand(1, 5) > 1;
$createdAt = $faker->dateTimeBetween('-6 months', '-1 day');
return [
'category_id' => rand(1, 10),
'user_id' => 1,
'title' => $title,
'slug' => Str::slug($title),
'excerpt' => $faker->text(rand(100, 400)),
'content_raw' => $text,
'content_html' => $text,
'is_published' => $isPublished,
'published_at' => $isPublished ? $faker->dateTimeBetween('-6 months', '-1day') : null,
'created_at' => $createdAt,
'updated_at' => $createdAt
];
});
DatabaseSeeder
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
$this->call(UserTableSeeder::class);
$this->call(BlogCategorySeeder::class);
factory(BlogPost::class, 1)->create();
}
}
When i run php artisan migrate:fresh --seed i got this error.
Tables users and blog_categories seeds successfully, but error appear for blog_categories.
I don't understand why.
Field user_id exists in $fillable in BlogPost Model.
If i change migration for blog_posts and add a nullable for user_id, than seed work, but user_id is null. But i don't need that.
Thansk in advance.
In Blog Post Model
Change user relationship to
public function owner()
{
return $this->belongsTo(User::class);
}
In User Model
Add this relationship
public function blogposts()
{
return $this->hasMany(BlogPost::class);
}
In Database seeder don't use UserSeeder Directly create user in DatabaseSeeder
public function run()
{
$user = User::create([
'name' => "Your name",
'email' => "youremail#gmail.com",
'password' => Hash::make('YourPassword')
]);
$this->call(BlogCategorySeeder::class);
$user->blogposts()->saveMany(BlogPost::factory(1));
}
In BlogPost Factory remove user_id
return [
'category_id' => rand(1, 10),
'title' => $title,
'slug' => Str::slug($title),
'excerpt' => $faker->text(rand(100, 400)),
'content_raw' => $text,
'content_html' => $text,
'is_published' => $isPublished,
'published_at' => $isPublished ? $faker->dateTimeBetween('-6 months', '-1day') : null,
'created_at' => $createdAt,
'updated_at' => $createdAt
];
fillable is not required when you are using Seeder to insert data.
If you want to insert each and every column in database then you can use guarded property which is opposite of fillable.

Laravel seeder gets stuck and returns ErrorException Array yo string conversion

public function up()
{
Schema::create('settings', function (Blueprint $table) {
$table->id();
$table->string('name', 40)->unique();
$table->json('value');
$table->timestamps();
});
//seeder to insert FTP settings
DB::table("settings")->insert([
'name' => 'FTP_SETTINGS',
'value' => ['host' => '192.168.5.190', 'username'=> 'Alessandro', 'password' => 'Alessandro', 'port' => '21']
]);
}
I'm doing this migration with a seeder after that (I've also put it into the seeder section but has the same issue) but i get the ErrorException Array to string conversion.
Probably is something with the value propriety but I cannot understand what I'm doing wrong..many thanks for your help.
You are trying to insert array values into json filed.
Try instead:
DB::table("settings")->insert([
'name' => 'FTP_SETTINGS',
'value' => json_encode(['host' => '192.168.5.190', 'username'=> 'Alessandro', 'password' => 'Alessandro', 'port' => '21'])
]);

Factory model relationships in Laravel

I have 2 tables named Users and Users_meta. Both are sharing One-To-One relationship. I would like to insert dummy data with the help of seeding. I am able to do that, the only thing that is driving me crazy is that, I am unable to establish relationship between users and users_meta table with user_id as foreign key. I tried few ways but that either creates duplicate entires with same user_id or keeps repeating the same user_id.
What exactly I would like is; when creating for example 100 records, after first user record insertion, it should take the same user's user_ID, add it to users_meta table's user_id field and repeat the insertion till 100 fake records.
Any help on this would be greatly appreciated
Code in : UserFactory.php
$factory->define(App\User::class, function (Faker $faker) {
static $password;
return [
'username' => $faker->userName,
'email' => $faker->unique()->safeEmail,
'password' => $password ?: $password = bcrypt('secret'),
'referral_code' => str_random(10),
'referred_by_code' => str_random(10),
'role' => $faker->randomElement(['administrator', 'user', 'volunteer']),
'remember_token' => str_random(10),
]; });
Code in : UsersMetaFactory.php
$factory->define(App\Usersmeta::class, function (Faker $faker) {
return [
'user_id' => $faker->randomElement(\App\User::pluck('id')->toArray()),
'first_name' => $faker->firstname,
'last_name' => $faker->lastname,
'gender' => $faker->randomElement(['male', 'female']),
'date_of_birth' => $faker->dateTimeThisCentury->format('Y-m-d'),
'address' => $faker->address,
'city' => $faker->city,
'state' => $faker->state,
'zip_code' => $faker->postcode,
'country' => $faker->country,
'cell_phone' => $faker->e164PhoneNumber,
'bitcoin_address' => str_random(16),
'monero_address' => str_random(16),
'security_question' => $faker->realText($maxNbChars = 20, $indexSize = 2),
'security_answer' => $faker->realText($maxNbChars = 40, $indexSize = 2),
'is_founder' => $faker->boolean($chanceOfGettingTrue = 50),
'status' => $faker->randomElement(['active', 'inactive']),
'terms' => $faker->boolean
]; });
The randomElement() method gives me random id which violates one to one relationship principal and my app breaks down. I would like it should fetch id from users table and pass the same id as user_id to users_meta table and continue generating fake records.
CreateUsersTable migration class
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('username')->unique();
$table->string('email')->unique();
$table->string('password');
$table->string('referral_code')->unique();
$table->string('referred_by_code');
$table->enum('role', ['administrator', 'user', 'volunteer'])->nullable();
$table->rememberToken();
$table->timestamps();
});
}
CreateUsersMetaTable migration class
public function up()
{
Schema::create('users_meta', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->string('first_name');
$table->string('last_name');
$table->enum('gender', ['male', 'female'])->nullable();
$table->string('date_of_birth')->nullable();
$table->string('address')->nullable();
$table->string('city')->nullable();
$table->string('state')->nullable();
$table->string('zip_code')->nullable();
$table->string('country');
$table->string('cell_phone');
$table->string('bitcoin_address')->nullable();
$table->string('monero_address')->nullable();
$table->string('security_question');
$table->string('security_answer');
$table->string('is_founder')->nullable();
$table->enum('status', ['active', 'inactive'])->nullable();
$table->string('terms');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('users_meta');
Schema::enableForeignKeyConstraints();
}
You should remove this line:
'user_id' => $faker->randomElement(\App\User::pluck('id')->toArray()),
And use relationship when creating a new model. Here's a modified example from the docs:
factory(App\User::class, 50)->create()->each(function ($u) {
$u->usersmeta()->save(factory(App\Usersmeta::class)->make());
});

Troubles with Eloquent

I'm rather new to Eloquent (and ORM's as a whole really). I have done rather a lot of background reading but can't quite get my head around the relationships in Eloquent.
I have a Car model that relates to a Color model, a Make model and a Model model.
I pass my Car::getAll() through to my View as $cars. When I call dd(toArray($cars)) I get the following:
array (size=1)
0 =>
array (size=12)
'id' => string '1' (length=1)
'registration' => string '123' (length=3)
'make' =>
array (size=5)
'id' => string '1' (length=1)
'title' => string 'Ford' (length=4)
'slug' => string 'ford' (length=4)
'created_at' => string '2014-06-26 21:30:23' (length=19)
'updated_at' => string '2014-06-26 21:30:23' (length=19)
'model' =>
array (size=5)
'id' => string '1' (length=1)
'title' => string 'Mustang' (length=7)
'slug' => string 'mustang' (length=7)
'created_at' => string '2014-06-26 21:30:41' (length=19)
'updated_at' => string '2014-06-26 21:30:41' (length=19)
'color' =>
array (size=5)
'id' => string '1' (length=1)
'title' => string 'Red' (length=3)
'slug' => string 'red' (length=3)
'created_at' => string '2014-06-26 21:30:03' (length=19)
'updated_at' => string '2014-06-26 21:30:03' (length=19)
'year' => string '1991' (length=4)
'is_classic' => string '1' (length=1)
'price' => string '999.00' (length=6)
'sold' => string '0' (length=1)
'active' => string '1' (length=1)
'created_at' => string '2014-06-26 22:17:27' (length=19)
'updated_at' => string '2014-06-26 22:17:27' (length=19)`
Which appears to be right to me, however when I have:
foreach ($cars as $car) {
echo $car->color-title;
}
I get a "Trying to get property of non-object" error.
My Models are as follows:
Car.php
class Car extends \Eloquent {
protected $fillable = ['color_id'];
public function color() {
return $this->belongsTo('Color', 'id');
}
public function model() {
return $this->belongsTo('Model', 'id');
}
public function make() {
return $this->belongsTo('Make', 'id');
}
public static function getAll() {
return Car::with('color', 'make', 'model')->where('active', 1)->get();
}
}
Color.php
class Color extends \Eloquent {
protected $fillable = ['title', 'slug'];
public function cars() {
return $this->hasMany('Car', 'color');
}
}
Make.php
class Make extends \Eloquent {
protected $fillable = [];
public function cars() {
return $this->hasMany('Car', 'make');
}
}
Model.php
class Model extends \Eloquent {
protected $fillable = [];
public function cars() {
return $this->hasMany('Car', 'model');
}
}
Any help would be very much appreciated. Thank you
EDIT:
Sorry I should have included my schema up methods:
CreateMakesTable
public function up()
{
Schema::create('makes', function(Blueprint $table)
{
$table->increments('id');
$table->string('title');
$table->string('slug');
$table->timestamps();
});
}
CreateModelsTable
public function up()
{
Schema::create('models', function(Blueprint $table)
{
$table->increments('id');
$table->integer('make')->unsigned();
$table->string('title');
$table->string('slug');
$table->timestamps();
});
Schema::table('models', function(Blueprint $table)
{
$table->foreign('make')->references('id')->on('makes')->onDelete('cascade');
});
}
CreateColorsTable
public function up()
{
Schema::create('colors', function(Blueprint $table)
{
$table->increments('id');
$table->string('title');
$table->string('slug');
$table->timestamps();
});
}
CreateCarsTable
public function up()
{
Schema::create('cars', function(Blueprint $table)
{
$table->increments('id');
$table->string('registration');
$table->integer('make')->unsigned();
$table->integer('model')->unsigned();
$table->integer('year');
$table->integer('color')->unsigned();
$table->boolean('is_classic');
$table->float('price');
$table->boolean('sold');
$table->boolean('active');
$table->timestamps();
});
Schema::table('cars', function(Blueprint $table)
{
$table->foreign('make')->references('id')->on('makes')->onDelete('cascade');
$table->foreign('model')->references('id')->on('models')->onDelete('cascade');
$table->foreign('color')->references('id')->on('colors')->onDelete('cascade');
});
}
Like Jason pointed out the error is caused by null returned from one of those relationships. But the problem with your setup is, that the relationship definitions are wrong.
So first make them right:
// it goes like this:
// belongsTo('Model', 'foreign_key_on_this_model', 'primary_key_on_related')
public function color() {
return $this->belongsTo('Color', 'color'); // primary key is id so no need to specify
}
hasMany relations on the other models are OK.
Then in that loop:
foreach ($cars as $car)
{
if (count($car->color))
{
// do something with color
}
}
For the reason I'm using count read this: Laravel check if related model exists
You can also return only cars that have related color, make and whatever you need like below:
$cars = Car::has('color')->has('make')...

Resources