How to insert data to database using seeder in Laravel? - php

I have a problem with seeder. My data not insert to the database. The table customers are created but data not insert to database. Below I show me code. I use
php artisan migrate:fresh --seed
Migration
public function up()
{
Schema::create('customers', function (Blueprint $table) {
$table->id();
$table->string('first_name', 20);
$table->string('last_name', 30);
$table->string('email')->unique();
$table->string('phone_number')->unique();
$table->timestamps();
});
}
Model
class Customer extends Model
{
use HasFactory;
protected $fillable = [
'first_name',
'last_name',
'email',
'phone_number'
];
}
Factory
class CustomerFactory extends Factory
{
/**
* Define the model's default state.
*
* #return array<string, mixed>
*/
public function definition()
{
return [
'first_name' => fake()->firstName(),
'last_name' => fake()->lastName(),
'email' => fake()->unique()->safeEmail(),
'phone_number' => fake()->unique()->phoneNumber()
];
}
}
Seeder
class CustomersTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
Customer::factory(20)->create();
}
}
Now show me error
at C:\laragon\www\zadanie-rekrutacyjne\vendor\laravel\framework\src\Illuminate\Container\Container.php:1307
1303▕ * #return string
1304▕ */
1305▕ public function getAlias($abstract)
1306▕ {
➜ 1307▕ return isset($this->aliases[$abstract])
1308▕ ? $this->getAlias($this->aliases[$abstract])
1309▕ : $abstract;
1310▕ }
1311▕
1 C:\laragon\www\zadanie-rekrutacyjne\vendor\laravel\framework\src\Illuminate\Foundation\Application.php:843
Illuminate\Container\Container::getAlias(Object(Illuminate\Database\Eloquent\Collection))
2 C:\laragon\www\zadanie-rekrutacyjne\vendor\laravel\framework\src\Illuminate\Database\Seeder.php:129
Illuminate\Foundation\Application::make(Object(Illuminate\Database\Eloquent\Collection))

Within the DatabaseSeeder class, you have to call the method to execute additional seed classes.
/**
* Run the database seeders.
*
* #return void
*/
public function run()
{
$this->call([
CustomersTableSeeder::class,
]);
}
As per the official doc:
Within the DatabaseSeeder class, you may use the call method to
execute additional seed classes. Using the call method allows you to
break up your database seeding into multiple files so that no single
seeder class becomes too large. The call method accepts an array of
seeder classes that should be executed:
Ref: Calling Additional Seeders

Related

Not understanding why I have to use json_decode twice. Laravel Migrations and Model

So consider the following migration:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateAdventureLogs extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('adventure_logs', function (Blueprint $table) {
$table->id();
$table->bigInteger('character_id')->unsigned();
$table->foreign('character_id')
->references('id')->on('characters');
$table->bigInteger('adventure_id')->unsigned();
$table->boolean('in_progress')->nullable()->default(false);
$table->boolean('complete')->nullable()->default(false);
$table->integer('last_completed_level')->nullable();
$table->json('logs')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('adventure_logs');
}
}
Notice the json column I create. $table->json('logs')->nullable();
From here, lets create a model:
use Illuminate\Database\Eloquent\Model;
class AdventureLog extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'character_id',
'adventure_id',
'complete',
'in_progress',
'last_completed_level',
'logs',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'complete' => 'boolean',
'in_progress' => 'boolean',
'last_completed_level' => 'integer',
];
public function getLogsAttribute($value) {
return json_decode(json_decode($value));
}
public function setLogsAttribute($value) {
$this->attributes['logs'] = json_encode($value);
}
public function character() {
return $this->belongsTo(Character::class);
}
public function adventure() {
return $this->hasOne(Adventure::class, 'id', 'adventure_id');
}
}
Notice this method:
public function getLogsAttribute($value) {
return json_decode(json_decode($value));
}
this is wrong. Obviously.
So the json that is stored is:
[{"adventure":"sample"}]
So when I call: $character->adventureLogs()->first()->logs I get: [{"adventure":"sample"}].
But if we change the function to what it's suppose to be:
public function getLogsAttribute($value) {
return json_decode($value);
}
then I get: "[{"adventure":"sample"}]".
I store data by doing:
AdventureLog::create([
// .... Other attributes
'logs' => ['adventure' => 'sample']
]);
So what am I doing wrong where I have to wrap the first json_decode into another one? I should not have to do that.
From the docs (https://laravel.com/docs/7.x/eloquent-mutators#array-and-json-casting):
... if your database has a JSON or TEXT field type that contains serialized JSON, adding the array cast to that attribute will automatically deserialize the attribute to a PHP array when you access it on your Eloquent model
So just add
protected $casts = [
...
'logs' => 'array',
];

Laravel 5.3 Does protected variables in a Model act as constructor

I'm new to Laravel and I noticed some are similar to Java, some aren't. I guess it's because it uses OOP style.
I'm following a video tutorial for beginners and came across the protected modifier (if I'm correct).
I originally learned programming in Java. Below are three php file definitions.
Does the protected $fillable in the Product class act like a constructor in Java which requires you to supply values before you can create an instance of the class? (in this case, Product Class)
ProductTableSeeder.php
<?php
use Illuminate\Database\Seeder;
class ProductTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$product = new \App\Product([
'imagePath' => 'someImagePathURL',
'title' => 'Harry Potter',
'description' => 'Super cool - at least as a child.',
'price' => 10
]);
$product->save();
}
}
Product.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $fillable = ['imagePath','title','description','price'];
}
create_products_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('imagePath');
$table->string('title');
$table->text('description');
$table->integer('price');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('products');
}
}
The line $product = new \App\Product I understand to be the instantiation part.
I'd appreciate any useful explanation to this.
Thank you.
protected $fillable = ['imagePath','title','description','price'];
It means, the field names that are given in this array can only be inserted into database from our side. Like, it is only allowed to fill values from us.
In clear, referred from document.
The $fillable property means an array of attributes that you want to be mass assignable
And,
The $guarded property means an array of attributes that you do not want to be mass assignable
Reference : https://laravel.com/docs/5.3/eloquent#mass-assignment

Database Seeding in Laravel 5.1

I am using laravel 5.1. I am trying to run database seeding command.
My table name is users
My migration file is as below
2015_11_09_194832_create_users_table.php
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('users');
}
}
DatabaseSeeder.php
<?php
use App\User;
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
Model::unguard();
$this->call(UsersTableSeeder::class);
Model::reguard();
}
}
UsersTableSeeder.php
<?php
// DatabaseSeeder.php
use App\User;
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
class UsersTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
Model::unguard();
DB::table('users');
$users = array(
['name' => 'Ryan Chenkie', 'email' => 'ryanchenkie#gmail.com', 'password' => Hash::make('secret')],
['name' => 'Chris Sevilleja', 'email' => 'chris#scotch.io', 'password' => Hash::make('secret')],
['name' => 'Holly Lloyd', 'email' => 'holly#scotch.io', 'password' => Hash::make('secret')],
['name' => 'Adnan Kukic', 'email' => 'adnan#scotch.io', 'password' => Hash::make('secret')],
);
// Loop through each user above and create the record for them in the database
foreach ($users as $user)
{
User::create($user);
}
Model::reguard();
}
}
While I am trying to run seeding command php artisan db:seed I am getting below error.
[ReflectionException]
Class UsersTableSeeder does not exist
Can anyone help me in this regard ??
I've run in to this issue a few time when I've added seeders either in a new project or to an existing project where I want to add some data to test.
Both jedrzej.kurylo and Alex were on the right track, composer dump-autoload which will regenerate your autoload files and include the seeder(s) you've just added.

Laravel 5 database will not seed

I have the following:
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateFinanceAccountsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('finance_accounts', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('created_by')->index();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('finance_accounts');
}
}
And the seeder:
class FinanceAccountsTableSeeder extends Seeder
{
public function run()
{
DB::table('finance_accounts')->delete();
App\Models\Finance\FinanceAccount::create([
'name' => 'Default account',
'created_by' => 1
]);
}
}
Which is called via:
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
Model::unguard();
$this->call('UserRolesTableSeeder');
$this->call('UserTableSeeder');
$this->call('FinanceTransactionsTableSeeder');
$this->call('FinanceAccountsTableSeeder');
$this->call('CurrencyTableSeeder');
$this->call('UserProfileTableSeeder');
}
}
However, the table is created fine, but no data gets inserted.
The seeders for all my other tables work perfectly, just not for this one.
Does anyone have an idea why?
namespace App\Models\Finance;
use Illuminate\Database\Eloquent\Model;
class FinanceAccount extends Model {
protected $table = 'finance_accounts';
}

Use of undefined constant when seeding

I get this error when trying to seed my database with php artisan db:seed:
[ErrorException] Use of undefined constant username - assumed 'username'
I've checked the Laravel docs and the syntax looks correct, however I'm not sure what I'm messing up on this.
<?php
class DatabaseSeeder extends Seeder {
/**
* Run the database seeds.
*
* #return void
*/
public function run(){
Eloquent::unguard();
$this->call('UsersTableSeeder');
}
}
class UsersTableSeeder extends Seeder {
public function run(){
User::create([
'username' => 'Ziggy',
'email' => 'ziggy#stardust.com',
'password' => '1234'
]);
}
}
EDIT: I've added the User model:
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
public $timestamps = false;
protected $fillable = [username, password];
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
}
Here is the migration file used:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->string('username');
$table->string('email')->unique();
$table->string('password');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('users', function(Blueprint $table)
{
Schema::drop('users');
});
}
}
In User class, change this:
protected $fillable = [username, password];
to this
protected $fillable = ['username', 'password'];
The way it has been declared, PHP took them as constants and not strings

Categories