Migrate failing in laravel 4.2.* - php

I'm trying to write a simple REST API for laravel 4.2. Here is my code:
This is the command to generate two tables:
php artisan migrate:make create_users_table --table=users --create
php artisan migrate:make create_urls_table --table=urls --create
Then I added this code in up section of create_users_table.php:
$table->increments('id');
$table->string('username')->unique();
$table->string('password');
$table->timestamps();
I added this code in up section of create_urls_table.php:
$table->increments('id');
$table->integer('user_id');
$table->string('url');
$table->string('description');
$table->timestamps();
My db configurations are like this:
'mysql' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'read_it_later',
'username' => '<username>',
'password' => '<password>',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
Then I added this to UserTableSeeder.php in seeds folder in database folder:
<?php
class UserTableSeeder extends Seeder {
public function run()
{
DB::table('users')->delete();
User::create(array(
'username' => 'firstuser',
'password' => Hash::make('first_password')
));
User::create(array(
'username' => 'seconduser',
'password' => Hash::make('second_password')
));
}
}
Then I uncommented $this->call('UserTableSeeder') in DatabaseSeeder.php file.
Then I ran this command:
php artisan migrate
And I got the following error:
**************************************
* Application In Production! *
**************************************
Do you really wish to run this command? y
Migration table created successfully.
[Illuminate\Database\QueryException]
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'read_it_later.users' doesn't exist (SQL: alter table `users` add `id` int unsigned not
null auto_increment primary key, add `username` varchar(255) not null, add `password` varchar(255) not null, add `created_at` timestamp default 0
not null, add `updated_at` timestamp default 0 not null)
[PDOException]
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'read_it_later.users' doesn't exist
migrate [--bench[="..."]] [--database[="..."]] [--force] [--path[="..."]] [--package[="..."]] [--pretend] [--seed]
How can I fix this error?

I just found out that I was using wrong command to generate migration tables.
I used the following commands:
php artisan migrate:make create_users_table --create=users
php artisan migrate:make create_urls_table --create=urls
Then I added my code to those files and tried these commands:
php artisan migrate
php artisan db:seed
And it worked

Related

Can I ignore specific migrations when running Laravel unit tests

When running tests in Laravel (php artisan test), I get an error 'duplicate column name: created_at'. This only occurs when i have field additions in the migrations directory. Am i able to ignore specific files when running Laravel tests? Or is there another way to get round this issue?
migrations:
if i just have this table, the tests work fine:
2021_06_18_134444_create_users_tables.php
after creating this migration, the tests fail:
2021_07_08_135544_add_timestamps_to_all_tables.php
a simple test:
use RefreshDatabase;
public function test_redirect_to_home_page_after_login()
{
$user = User::factory()->make([
'name' => 'Test',
'email' => 'test#hotmail.com',
'password' => bcrypt('123456')
]);
$response = $this->post('login', [
'name' => 'Test',
'email' => 'test#hotmail.com',
'password' => '123456'
]);
$response->assertRedirect('/');
$response->assertSessionHasErrors();
}

Laravel Foreign key Referencing table in External database?

I'm new to Laravel and databases in general. I'm writing a web application for student evaluations. I have an existing MySQL database that contains everything I need already; however, I am using Laravel's auth user table and trying to add a foreign key that references a Teacher table in the MySQL database. I keep getting the following error...
php artisan migrate:fresh
In Connection.php line 664:
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
(SQL: alter table users add constraint users_teacher_id_foreign
foreign key (teacher_id) references p4j.teacher (teacher_id))
In Connection.php line 458: SQLSTATE[HY000]: General error: 1215 Cannot
add foreign key constraint
My code is as follows...
config/database.php
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DP_PORT', '3306'),
'database' => env('DB_DATABASE', 'p4j'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DP_PASSWORD', '**mypassword**'),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
],
database/migrations/2014_10_12_000000_create_users_table.php
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->integer('teacher_id')->unsigned();
$table->rememberToken();
$table->timestamps();
});
Schema::table('users', function (Blueprint $table) {
$table->foreign('teacher_id')->references('teacher_id')->on('p4j.teacher');
});
}
app/User.php
protected $fillable = [
'name', 'email', 'password', 'teacher_id'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
You just need to make sure that the data type of the foreign key (p4j.teacher.teacher_id) corresponds to the same data type of the teacher_id column in your users table.
We need to see the structure of the p4j.teacher table.
Couple possible issues and solutions are that your db engine is not INNODB or loading order of migration files is incorrect. For the first solution you need to add $table->engine = 'InnoDB'; inside of Schema::create and if this doesn't fix the issue, i'll need you to post the names of your users and teacher migrations
Possible fix:
Both PRIMARY KEY constraint and UNIQUE constraint uses to enforce Entity integrity (defines a row as a unique entity for a particular table), but primary keys do not allow null values. Specifies the column that uniquely identifies a row in the table. The identified columns must be defined as NOT NULL.
And since laravel increment function also
Auto-incrementing UNSIGNED INTEGER (primary key) equivalent column.
Simply removing ->default(null); and rerunning migrations should potentially fix the problem.

customising Job and job table in Laravel queue/ rename jobs table

When I try php artisan queue:table
It gave me the following error
[InvalidArgumentException]
A CreateJobsTable migration already exists.
It is because I have already the migration named CreateJobsTable for other purpose. I cannot rename this table and migration . Is there any way to rename the migration to CreateJobsQueueTable or some thing relevant?
can we rename the jobs table that artisan creates with 'queue:table'?
Yes. Edit this file config\queue.php:
<?php
return [
....
'connections' => [
....
'database' => [
'driver' => 'database',
'table' => 'jobs', <------ Edit this to something else
'queue' => 'default',
'retry_after' => 90,
],
....
],
....
];
Change the table name to other value, and it should pick up by the TableCommand. Check out Illuminate\Queue\Console\TableCommand on how it uses this value. It's pretty much straightforward :)

Use one Laravel migrations table per database

I work in a project that uses multiple databases. It seems like Laravel only uses the migrations-table in the database that is set as default. I would like one migrations table per database that logs the migrations that have been done to that specific database. Is this possible?
I have defined the databases in the config like this:
'connections' => [
'db1' => array(
'driver' => 'mysql',
'host' => 'db1.host',
'database' => 'db1',
'username' => 'username',
'password' => 'password',
),
'db2' => [
'driver' => 'mysql',
'host' => 'db2.host',
'database' => 'db2',
'username' => 'username',
'password' => 'password',
]
],
I also made the first database (db1) the default one
'default' => 'db1'
I install the migrations table on both databases
artisan migrate:install --database=db1
artisan migrate:install --database=db2
After that i proceed to create a couple of database specifc migrations
Create table test1 in db1 database:
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTest1Table extends Migration
{
public function up()
{
Schema::connection('db1')->create('test1', function(Blueprint $table)
{
$table->increments('id')->unsigned();
});
}
public function down()
{
Schema::connection('db1')->drop('test1');
}
}
Create table test2 in db2 database:
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTest2Table extends Migration
{
public function up()
{
Schema::connection('db2')->create('test2', function(Blueprint $table)
{
$table->increments('id')->unsigned();
});
}
public function down()
{
Schema::connection('db2')->drop('test2');
}
}
I now run the migrations
artisan migrate
Expected outcome
db1.migrations
+-----------------------------+-------+
| migration | batch |
+-----------------------------+-------+
| create_test1_table_in_db1 | 1 |
+-----------------------------+-------+
db2.migrations
+-----------------------------+-------+
| migration | batch |
+-----------------------------+-------+
| create_test2_table_in_db2 | 1 |
+-----------------------------+-------+
Actual outcome
db1.migrations
+-----------------------------+-------+
| migration | batch |
+-----------------------------+-------+
| create_test1_table_in_db1 | 1 |
| create_test2_table_in_db2 | 1 |
+-----------------------------+-------+
db2.migrations
+-----------------------------+-------+
| migration | batch |
+-----------------------------+-------+
Empty set
Article on usage of multiple database usage in Laravel -
https://stackcoder.in/posts/laravel-7x-multiple-database-connections-migrations-relationships-querying
Use the --database parameter with the migrate command and store the migrations for each database in separate directories.
You could have separate directories in app/database/migrations for each of your database (in your case db1 and db2) and store the appropriate migrations in each directory. Then you could run the migrations like this:
artisan migrate --database="db1" --path="app/database/migrations/db1"
artisan migrate --database="db2" --path="app/database/migrations/db2"
This way your migrations table will be independent for each database.
If you want to go the extra mile and automate the process you could create your custom command that will run all the migrations at once. You can create the command like this (use make:console for Laravel 5.0 up to 5.2 or make:command for Laravel 5.2+):
artisan command:make MigrateAllCommand --command=migrate:all
This will create a new file app/commands/MigrateAllCommand.php. Your command's fire method would look something like this:
public function fire()
{
foreach (Config::get('database.connections') as $name => $details)
{
$this->info('Running migration for "' . $name . '"');
$this->call('migrate', array('--database' => $name, '--path' => 'app/database/migrations/' . $name));
}
}
This will work provided the name of the database configuration key is the same as the migration directory name. You can then just call it like this:
artisan migrate:all
You can check the Laravel Command Docs for more info.

Benefit Of Migrations in Laravel

as In laravel we Use Migrations to Create Tables and then Seeders to seed out table, am not getting its benefit, as we can do that in normal way by just going to PHPMYADMIN then what we need to that, as we code many lines for it, but how can we justify those lines of code ?
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateItemsTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('items', function(Blueprint $table)
{
$table->increments('id');
$table->integer('owner_id');
$table->string('name');
$table->boolean('done');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('items');
}
}
it is true that migrations are being created by php artisan commands, But what is the benefit of them? as we have an alternate to do that?
same for the Seeder files as we code many lines for it
class ItemTableSeeder extends Seeder{
public function run(){
DB::table('items')->delete();
$items= array(
array(
'owner_id' => '1',
'name' => 'Watch The Spectacular Now',
'done' => True
),
array(
'owner_id' => '2',
'name' => 'Watch Avengers',
'done' => False
),
array(
'owner_id' => '1',
'name' => 'Watch The Iron man',
'done' => False
),
array(
'owner_id' => '1',
'name' => 'Divergent',
'done' => False
),
array(
'owner_id' => '1',
'name' => 'Bat Man',
'done' => False
),
array(
'owner_id' => '1',
'name' => 'X-Men Days Of Future Past',
'done' => False
)
);
DB::table('items')->insert($items);
}
}
The main benefit is that you will do it in your development server/station, and you may change the schema many times in development, migrate, rollback migrations, and re-migrate them, and as soon as your application id done, you don't have to remember what you have to do in your production environment, Laravel will do it automatically for you.
Using PHPMyAdmin, you would have to create tables and edit fields manually locally and in your remote server, and you would risk forgetting something and breaking your application. And, if you have more than one server serving your application, the problem is bigger.
Migrations and seeds are database versioning. Imagine that one day you fall in love with, say PostgreSQL or anything other than MySQL. Then imagine you'd like to do some tests with more than several rows of data.. Would you run PHPMYADMIN's equivalent and insert 100, 1000 or 10000 rows?
So now check this out:
// migration
class CreateCommentsTable extends Migration {
public function up()
{
Schema::create('comments', function(Blueprint $table) {
$table->increments('id');
$table->string('body');
$table->integer('author_id')->unsigned();
$table->integer('post_id')->unsigned();
$table->timestamps();
});
}
// seeder
class CommentsTableSeeder extends Seeder {
public function run()
{
Eloquent::unguard();
$faker = Faker::create();
foreach(range(1, 1000) as $index)
{
Comment::create([
'body' => $faker->sentence(10),
'author_id' => rand(1,20),
'post_id' => rand(1,150)
]);
}
}
Faker is a great tool you can find here: https://github.com/fzaninotto/Faker
All you need to do now is run artisan migrate --seed.
Of course there are more advantages than automating seeds, you can alter your tables with migrations in case you want to change your schema and so on.
Migration files maintains the schema of the tables. Using migration, you may never have to go to phpMyAdmin (except for creating a DB). Once done you can simply run the command 'php artisan migrate' and create the tables from the PHP side itself. Also you will never have to worry about the DB environment (MySql, Posgres, Sql Lite etc) as the migration does not truly depend on the environment to which you are migrating the tables.
Seeding helps in creating, for example, different roles (Admin, User, Editor etc) within your application. You will have to just create the seeder files and run the 'php artisan db:seed' command to populate data to the tables from the php side. Also seeds help in creating test data.

Categories