Laravel - Seeding isn't refreshing - php

I'm trying to seed into an orders migration file, however upon using the command: php artisan migrate:refresh --seed, the following error is being returned.
ReflectionException : Class OrdersTableSeeder does not exist
Either I'm stupid or Laravel is broken.
Seeder:
class OrdersTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
DB::table('orders')->insert([
'user_id' => 1,
'product_id' => 1,
'quantity' => 10,
'updated_at' => DB::raw('CURRENT_TIMESTAMP')
]);
DB::table('orders')->insert([
'user_id' => 1,
'product_id' => 2,
'quantity' => 5,
'updated_at' => DB::raw('CURRENT_TIMESTAMP')
]);
}
}
Migration:
Schema::create('orders', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id'); //fk
$table->integer('product_id'); //fk
$table->integer('quantity');
$table->timestamps();
});

Class doesn't exists error seems that Laravel couldn't find the class named OrdersTableSeeder.
I hope that using the below command helps.
composer dump-autoload
Explanation:
Why do I have to run "composer dump-autoload" command to make migrations work in laravel?

Related

Trying to post to two database tables from one form - Laravel 8

I am using Laravel 8 and trying to get an application form to post to two tables in my database
From my 2 database migration files:
public function up() {
Schema::create('applicants', function (Blueprint $table) {
$table->id();
$table->string('apptitle');
$table->string('firstname');
$table->string('middlename')->nullable();
...
$table->timestamps();
});
}
public function up() {
Schema::create('applications', function (Blueprint $table) {
$table->id();
$table->integer('applicant_id');
$table->integer('user_id');
$table->integer('loanAmount');
$table->string('loanTerm');
...
$table->timestamps();
});
}
Models:
class Applicant extends Model {
use HasFactory;
protected $table = 'applicants';
protected $fillable = [
'apptitle', 'firstname', 'middlename'...
];
public function application() {
return $this->hasOne(Application::class);
}
}
class Application extends Model {
use HasFactory;
protected $table = 'applications';
protected $fillable = [
'applicant_id',
'user_id',
'loanAmount',
'loanTerm',
...
];
public function applicant() {
return $this->belongsTo(Applicant::class);
}
}
Controllers:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\Applicants\CreateApplicantRequest;
class ApplicantsController extends Controller {
...
public function store(CreateApplicantRequest $request) {
$applicant = Applicant::create([
'apptitle' => $request->apptitle,
'firstname' => $request->firstname,
'middlename' => $request->middlename,
...
]);
}
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Application;
use App\Models\Applicant;
use App\Models\User;
use App\Http\Requests\Applications\CreateApplicationRequest;
class ApplicationsController extends Controller {
...
public function store(CreateApplicationRequest $request) {
$application = Application::create([
'applicant_id' => $request->applicant_id,
'user_id' => 'required',
'loanAmount' => 'required',
'loanTerm' => 'required',
...
]);
}
}
Requests:
public function rules() {
return [
'apptitle' => 'required',
'firstname' => 'required',
'middlename',
...
];
}
public function rules() {
return [
'applicant_id' => 'required',
'user_id' => 'required',
'loanAmount' => 'required',
'loanTerm' => 'required',
...
];
}
web.php
Route::get('applicants','ApplicantsController#store');
Route::resource('applications', 'ApplicationsController');
Route::get('applications/{application}', 'ApplicationsController#show');
I am continually getting errors: The applicant id field is required. (If I make this field nullable the form does successfully post all other fields to the database.)
This is my first big Laravel project so any help would be greatly appreciated.
Update:
I have gone through the answers provided and am still getting the same error.
I feel the main issue is - when the form is filled out the applicant_id field for the newly created Applicant is not being captured and added to the applications table?
You can store data from one form into 2 tables like this.
Remove use App\Http\Requests\Applicants\CreateApplicantRequest; from your ApplicationsController and run the following cmd commands:
composer dump-autoload
php artisan cache:clear
php artisan config:clear
php artisan view:clear
php artisan route:clear
These commands clear all cache from your project.
Add nullable to your application migration applicant_id:
$table->integer('applicant_id')->nullable();
I finally was able to get my form posting correctly to both databases - a big thank you to all those that have helped me in this journey.
This is my updated store function in my ApplicationsController:
public function store(CreateApplicationRequest $request, Applicant $applicant)
{
$applicant = Applicant::create([
'apptitle' => $request->apptitle,
'firstname' => $request->firstname,
'middlename' => $request->middlename,
...
]);
$application = $applicant->application()->create([
'applicant_id' => $applicant->id,
'user_id' => auth()->id(),
'loanAmount' => $request->loanAmount,
'loanTerm' => $request->loanTerm,
...
]);
// redirect the user
return redirect(route('applications.index'));
}
I hope this answer helps someone else out!

Can't seed the database in Laravel

I'm currently seed my database in Laravel, migrations works properly and I am able to see the tables in SQL workbench. But when I run the command php artisan db:seed nothing happens.
I can't find the cause of it. I'm pretty new to Laravel.
DB name is 'Laravel', the table name is 'books'.
Seeder Code:
DB::table('books')->insert($books = [
['name' => 'Harry Potter', 'writer_name' => 'J.K. Rowling', 'isbn' => '9780739360385'],
['name' => 'Game of Thrones', 'writer_name' => 'George R.R. Martin', 'isbn' => '9780739308684'],
['name' => 'Harry Potter', 'writer_name' => 'J.R.R. Tolkien', 'isbn' => '9780563528807'],
['name' => 'The Lord of The Rings', 'writer_name' => 'J.R.R. Tolkien', 'isbn' => '9780563528883'],
['name' => 'The Silmarillion', 'writer_name' => 'J.R.R. Tolkien', 'isbn' => '9780007120604'],
['name' => 'Animal Farm', 'writer_name' => 'George Orwell', 'isbn' => '9780140862515'],
['name' => 'It', 'writer_name' => 'Stephan King', 'isbn' => '9781441738707'],
['name' => 'The Art of Deception', 'writer_name' => 'Kevin Mitnick', 'isbn' => '9780470249321'],
]);
foreach ($books as $book) {
Book::create($book);
}
Migration Code:
public function up()
{
Schema::create('books', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('writer_name');
$table->string('image')->nullable();
$table->string('isbn')->unique();
$table->timestamps();
});
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 overwhelmingly large. Pass the name of the seeder class you wish to run:
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$this->call([
UserSeeder::class,
PostSeeder::class,
CommentSeeder::class,
]);
}
You can also specify which seeder file to run by command php artisan db:seed --class=yourseedername
Also in you seeder code you are inserting same data twice one by DB query and another from Book model. So you are duplicating same data twice. I believe an error should be thrown as column violation saying integrity constraint violation as isbn for books are unique.

Problem with seeding users to database in Laravel

I am trying to seed users in database but I get error saying
Symfony\Component\Debug\Exception\FatalThrowableError : Call to a member function random() on bool
I have users table and genders table with gender_id in users table that points to Man or Woman column in genders table with hasMany relationship. I want to be able to write gender_id automatically in users table when I seed the database and create a new user. Currently with this code I get that error from above and NULL in gender_id column, but rest it inserts correctly in both users and genders table. When I remove random() function then it inserts always 1 in gender_id, but I want to be able to write 1 or 2 randomly. Also when I dump $genders it returns TRUE. Is there some way around this, any help is appreciated. Here is my code.
UserSeeder.php
<?php
use Carbon\Carbon;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
class UsersTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$genders = DB::table('genders')->insert([
[
'genders' => 'Woman',
],
[
'genders' => 'Woman Looking For Woman',
],
[
'genders' => 'Man',
]
]);
//dd($genders);
DB::table('users')->insert([
'gender_id' => $genders->random(),
'name' => 'authuser',
'email' => 'authuser#auth.com',
'email_verified_at' => now(),
'password' => Hash::make('auth123456'),
'age' => 18,
'remember_token' => Str::random(10),
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
]);
}
}
users table
<?php
use Illuminate\Support\Facades\Schema;
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->bigIncrements('id');
$table->unsignedBigInteger('gender_id')->nullable();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password')->default();
$table->integer('age')->default()->nullable();
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
genders table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateGendersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('genders', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('genders');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('genders');
}
}
User.php
public function gender()
{
return $this->belongsTo(Gender::class, 'gender_id', 'id');
}
Gender.php
public function users()
{
return $this->hasMany(User::class, 'gender_id', 'id');
}
You can pluck your id values from Gendre and do randomly on that like this:
$genders = DB::table('genders')->insert([
['genders' => 'Woman'],
['genders' => 'Woman Looking For Woman'],
['genders' => 'Man']
]);
$gendreIds = Genders::pluck('id');
DB::table('users')->insert([
'gender_id' => $gendreIds->random(),
...
]);
This will give you gender which exists in database.
Sometimes seed wouldn't give you id's from 1 to 3.
So I think it's not best solution to use rand(1,3).
Good luck!
In your user creation method
Instead of
'gender_id' => $genders->random(),
you can use this
'gender_id' => rand(1,3),
No need to add genders here.You can do that in other seeder or manually do that.Here in your genders id should be in 1,2 & 3 .fixed.THen you can use rand() function here.rand() is a php function .rand() define a random number & you can fixed it value like rand(min,max) so just here use this rand(1,3)
public function run()
{
$genders = DB::table('genders')->insert([
[
'genders' => 'Woman',
],
[
'genders' => 'Woman Looking For Woman',
],
[
'genders' => 'Man',
]
]);//your wish to seed this gender in here
DB::table('users')->insert([
'gender_id' => rand(1,3),
'name' => 'authuser',
'email' => 'authuser#auth.com',
'email_verified_at' => now(),
'password' => Hash::make('auth123456'),
'age' => 18,
'remember_token' => Str::random(10),
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
]);
}

Laravel 5.3 migration doesn't create tables

I created some migrations using the command php artisan migrate:make and then filled it and saved it with some fields. This is a fresh installation and the first migration to run.
I ran php artisan migrate and the migration completed successfully. However, while the migrations table IS created, and it has a single row with the filename and batch 1, there is no table.
Here's my migration file code:
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateFuelLocationsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
//
Schema::create('fuel_locations', function (Blueprint $table) {
$table->increments('id');
$table->string('uid');
$table->string('name');
$table->string('fuel_type');
$table->string('email');
$table->string('street');
$table->string('city');
$table->string('state');
$table->string('zip');
$table->string('phone');
$table->string('service_hours');
$table->string('payment_methods');
$table->string('payment_method_other');
$table->decimal('latitude', 3, 7);
$table->decimal('longitude', 3, 7);
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
//
Schema::dropIfExists('fuel_locations');
}
}
And a few lines from my config/database.php:
'mysql' => [
'driver' => 'mysql',
'database' => 'mydb',
'host' => 'localhost',
'username' => 'root',
'password' => '',
'charset' => env('DB_CHARSET', 'utf8'),
'collation' => env('DB_COLLATION', 'utf8_unicode_ci'),
'prefix' => env('DB_PREFIX', ''),
'timezone' => env('DB_TIMEZONE', '+00:00'),
'strict' => env('DB_STRICT_MODE', false),
],
I did try changing the host to 127.0.0.1 but that wouldn't connect. How can I fix it so that it does create the table like it's supposed to.
The problem is with the following lines:
$table->decimal('latitude', 3, 7);
$table->decimal('longitude', 3, 7);
You should be getting an exception similar to the following
[PDOException] SQLSTATE[42000]: Syntax error or access violation: 1427
For float(M,D), double(M,D) or decimal(M,D), M must be >= D (column
'latitude').
when you do the migration.
Change to the following
$table->decimal('latitude', 10, 7);
$table->decimal('longitude', 10, 7);
and it should work.
Numeric precision refers to the maximum number of digits that are present in the number

ErrorException array to string conversion on migrate --seed

I'm trying to set up my very first laravel project however when I try to have artisan to seed the database with faker it throws
[errorException] array to string conversion
I'm just working with the stock users migration file
and using the command php artisan migrate --seed
Any guidance would be greatly appreciated
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->string('role', array('user', 'admin', 'superuser'));
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('users');
}
}
and this UserTableSeeder that artisan generated for me
use Illuminate\Database\Seeder;
class UserTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
factory(App\User::class, 49)->create();
factory(App\User::class)->create([
'name' => 'admin',
'role' => 'admin',
]);
}
}
this is my Modelfactory.php
$factory->define(App\User::class, function ($faker) {
return [
'name' => $faker->name,
'email' => $faker->email,
'password' => str_random(10),
'remember_token' => str_random(10),
'role' => $faker->word->randomElement(array('user','superuser')),
];
});
$table->string('role', array('user', 'admin', 'superuser'));
You are selecting a type of string and then providing an array.
This is exactly what your error is talking about.
Your error is because of this line
$table->string('role', array('user', 'admin', 'superuser'));
change string to enum; ex:
$table->enum('role', array('user', 'admin', 'superuser'));
this will execute.
You say string but provide an array in this line:
$table->string('role', array('user', 'admin', 'superuser'));
You should use :
$table->enum('role', ['user', 'admin', 'superuser']);
For reference see here:
https://laravel.com/docs/5.8/migrations#creating-columns

Categories