I'm trying to learn Laravel, but it seems the documentation is written with faulty examples... I want to create a table migration, run it, and seed it with some content.
First:
php artisan make:migration create_projects_and_tasks_tables
With the following content:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProjectsAndTasksTables extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('projects', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->default('');
$table->string('slug')->default('');
$table->timestamps();
});
Schema::create('tasks', function (Blueprint $table) {
$table->increments('id');
$table->integer('project_id')->unsigned()->default(0);
$table->foreign('project_id')->references('id')->on('projects')->onDelete('cascade');
$table->string('name')->default('');
$table->string('slug')->default('');
$table->boolean('completed')->default(false);
$table->text('description');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('tasks');
Schema::drop('projects');
}
}
It migrated Ok. So I want to seed the projects table.
First:
php artisan make:seeder ProjectsTableSeeder
The contents:
<?php
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
class ProjectsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$projects = array(
['id' => 1, 'name' => 'Project 1', 'slug' => 'project-1', 'created_at' => new DateTime, 'updated_at' => new DateTime],
['id' => 2, 'name' => 'Project 2', 'slug' => 'project-2', 'created_at' => new DateTime, 'updated_at' => new DateTime],
['id' => 3, 'name' => 'Project 3', 'slug' => 'project-3', 'created_at' => new DateTime, 'updated_at' => new DateTime]
);
DB::table('projects')->insert($projects);
}
}
All set, I tried to rollback the migration, migrate and seed it:
php artisan migrate:refresh --seed
Rolled back: 2016_09_28_160459_create_projects_and_tasks_tables
Rolled back: 2014_10_12_100000_create_password_resets_table
Rolled back: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_100000_create_password_resets_table
Migrated: 2016_09_28_160459_create_projects_and_tasks_tables
[Symfony\Component\Debug\Exception\FatalThrowableError]
Call to undefined method Illuminate\Database\MySqlConnection::setTable()
And that's it. My table is empty, and the method DB::table() seems to not exist anymore in the framework, even if the 5.3 docs shows it. What can I do?
I'm using the Laravel Homestead vagrant box, so php version or composer isn't the issue. I'm also using MySQL as my database driver.
Once you have written your seeder classes, you may use the db:seed Artisan command to seed your database. By default, the db:seed command runs the DatabaseSeeder class, which may be used to call other seed classes. However, you may use the --class option to specify a specific seeder class to run individually:
php artisan db:seed
php artisan db:seed --class=UsersTableSeeder
Also You Can provide a seeder class reference to call method of DatabaseSeeder.php file
php artisan db:seed
will run the DatabaseSeeder.php file and invoke the run() meothd
So here you can provide list of Seed source like follow
public function run()
{
$this->call(CountriesTableSeeder::class);
$this->call(VendorTypesTableSeeder::class);
}
Reference : seeding
By default, the --seed option when passed to the migrate:refresh command will run
{YOUR_APP}/database/seeds/DatabaseSeeder.php
The make:migration artisan command will create your seed, but it won't add the seeder to the DatabaseSeeder.php file. You'll need to manually do this.
However, if you want to specify a particular seeder with migrate:refresh, then use the --seeder=YourSeeder option.
Add the following to the top of your seeder class:
use Illuminate\Support\Facades\DB;
Somehow, DB is not within the scope.
I got the exact same error. This was caused by typo obviously. Try to compare all the dataseed tables with other tables. You might have put \DB::class instead of \DB::table.
Related
i am trying to make a seed with:
php artisan make:seed
But, i get the error:
Not enough arguments (missing: "name").
I dont know why, this is the seed i am trying to make:
class ProfessionSeeder extends Seeder
{
public function run()
{
DB::table('professions')->insert([
'title' => 'Desarrollador Back End'
]);
}
}
This is the migration corresponding to the DB table...
class CreateProfessionsTable extends Migration
{
public function up()
{
Schema::create('professions', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title', 100);
$table->timestamps();
});
}
Any ideas of what is going on?
Thank you!
You can see what is required for a command by using artisan help:
php artisan help make:seed
Will output something like:
Description:
Create a new seeder class
Usage:
make:seeder <name>
Arguments:
name The name of the class
...
This command takes an argument for the name of the class you want to create.
php artisan make:seed ProfessionSeeder
I am learning Laravel.
Here is my migration file code.
class CreatePostTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('post', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned(); // i want to add this column after adding this line i runs the command refresh but it shows below errors.
$table->string('title');
$table->text('body');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('post');
}
}
Now I have a problem that whenever I run this command in terminal in PhpStorm:
php artisan migrate:refresh
it shows following errors:
PHP Fatal error: Class 'AddIsAdminColumnToPostTable' not found in C:\xampp\htdocs\cms\vendor\laravel\framework\src\Illuminate\Database\Migrations\Migrator.php on line 335
Symfony\Component\Debug\Exception\FatalErrorException]
Class 'AddIsAdminColumnToPostTable' not found
I tried composer dump-autoload in terminal solution from here but it's not working. I also used rollback command but still having issue.
How can make refresh this?
Artisan looks for migrations based on the file name. If you want it to be called something else: rollback, delete the migration, make a new migration. Or, change the file name to exactly match the class name.
For you, try changing
class CreatePostTable extends Migration
to
class AddIsAdminColumnToPostTable extends Migration
I am following a tutorial called Incremental API in laracasts by Jeffrey Way.
There is a different coding between Laravel 4 faker class seeding and laravel 5.4.
I still followed the same code lines from the tutorials "Seeders Reloaded". Now, I am stuck with "Class LessonTagTableSeeder does not exist"
TagTableSeeder
class TagsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$faker = Faker::create('App\Tag');
for($i=1; $i <= 10; $i++) {
DB::table('tags')->insert([
'name' => $faker->word,
'created_at' => \Carbon\Carbon::now(),
'updated_at' => \Carbon\Carbon::now(),
]);
}
}
LessonTagTableSeeder
use Illuminate\Database\Seeder;
use Faker\Factory as Faker;
use App\Lesson;
use App\Tag;
class LessonTagTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$faker = Faker::create();
$lessonIds = Lesson::pluck('id')->all();
$tagIds = Tag::pluck('id')->all();
for($i=1; $i <= 30; $i++) {
DB::table('lesson_tag')->insert([
'lesson_id' => $faker->randomElement($lessonIds),
'tag_id' => $faker->randomElement($tagIds)
]);
}
}
DatabaseSeeder
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
use App\Lesson;
use App\Tag;
use DB;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
DB::statement('SET FOREIGN_KEY_CHECKS=0');
Lesson::truncate();
Tag::truncate();
DB::table('lesson_tag')->truncate();
Model::unguard();
$this->call('LessonsTableSeeder');
$this->call('TagsTableSeeder');
$this->call('LessonTagTableSeeder');
DB::statement('SET FOREIGN_KEY_CHECKS=1');
}
I was able to seed TagsTableSeeder with php artisan db:seed --class=TagsTableSeeder
When i run "php artisan db:seed --class=LessonTagTableSeeder" , i am prompted with:
[ReflectionException]
Class LessonTagTableSeeder does not exist
Do you have any idea how to edit the code above? Any help is appreciated
When you make changes into the seeder files and it does not reflects your changes you need to run composer dump autoload.
you can use any one of the following commands
$ composer dump-autoload
$ composer du
$ composer dump
$ composer dump-autoload -o
Then try to run you command db:seed again and it reflects you changes.
what composer dump autoload do?
composer dump-autoload won’t download a thing. It just regenerates the list of all classes that need to be included in the project (autoload_classmap.php). Ideal for when you have a new class inside your project.
Ideally, you execute composer dump-autoload -o , for a faster load of your webpages. The only reason it is not default, is because it takes a bit longer to generate (but is only slightly noticeable)
Make sure the file is named as LessonTagTableSeeder.php and it's in the same directory as the other seeders. Then run this command:
composer du
After that try to execute the seeder again.
run this command and then try again
composer dump-autoload -o
Usually cache
php artisan cache:clear
composer update
php artisan serve
A pivot table, or association table, is a table which maps the relationship between two other tables, very useful for two tables which have a many-to-many relationship.
There are 3 critical lines of code which you supplied for the 'DatabaseSeeder':
$this->call('LessonsTableSeeder');
$this->call('TagsTableSeeder');
$this->call('LessonTagTableSeeder');
Based on what you wrote, you only ran the commands for the 'TagsTableSeeder' and the 'LessonTagTableSeeder'. You missed running the command for 'LessonsTableSeeder'.
In other words, you had records in the 'Tag' table, but none in the 'Lesson' table. Therefore there were no records associated between the two tables and SQL couldn't create a null association (pivot) table.
As a further note, the order of execution for seed operations is important when creating an association table. You must execute the seed command for the association table AFTER seeding the other two tables. The association table needs to know the unique identifiers in each of the other tables in order to create the relationships.
I'm new to using Laravel.
I have a .sql file where created a whole bunch of tables("CREATE TABLE my_table......."). Is there a way to somehow import these statements into Laravel? I could always manually rewrite these tables in raw php, but I feel that this would take too long and there is possibly an easier way to do it.
You would use migrations in Laravel to do this for example
I want to create a table called tasks I would use this command in artisan
php artisan make:model Task
This would create a model called task and a migration for this table.
You can then access the migration file and input something like this
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTasksTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('tasks', function (Blueprint $table) {
$table->increments('task_id');
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('tasks');
}
}
You would then run the artisan command to create this table
php artisan migrate
This then automatically creates your table.
Its a very useful feature and you can also rollback your migrations or even refesh it meaning it will remove the table and then reinstate it with no data in.
php artisan migrate:refresh
link to the docs
http://laravel.com/docs/5.1/migrations
Running "php artisan migrate" does nothing: no database modifications, no message(olso no "nothing to migrate"), no error.
No records are being added to table migrations as well.
Previously, the command "php artisan migrate" was working fine.
One of the migration files in folder database/migrations has this content:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class VidsTableEdit14 extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('vids', function(Blueprint $table)
{
//
$table->integer('test');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('vids', function(Blueprint $table)
{
//
});
}
}
How to make "php artisan migrate" working?
If the migration stops working suddenly there is probably a syntax error somewhere in one of your migrations. If you suddenly get a class not found error be suspicious of a syntax error.
This same happened me, when I was trying to add soft delete to my table.
I created the migration and in the Schema::table function I typed "$table->softDelete();". Instead of
$table->softDeletes();
Notice the 's' for plural, I tried running migration and didn't get any error or message. I made it plural and it worked.
And I noticed that you didn't make down function().Try adding:
Schema::drop('vids');
And run the migration again.
Error:
SQLSTATE[42S01]
Migrating: 2014_10_12_000000_create_users_table
Illuminate\Database\QueryException
-------------
[php artisan migrate]
Solution: Go to:
app\Http\Providers\AppServiceProvider
import ( use Illuminate\Support\Facades\Schema; )
And, inside the register() function, insert this code:
public function register()
{
Schema::defaultStringLength(191);
}
Then run:
php artisan migrate:fresh