It not work, I search so many ways, How can I change length of value in laravel 5
public function up()
{
Schema::table('articles', function (Blueprint $table) {
$table->string('name',50)->change();
});
}
Thank you all for reading!
Regarding documentation, your example should work:
Schema::table('users', function ($table) {
$table->string('name', 50)->change();
});
Just run php artisan migrate command to execute it.
At least in Laravel 5.6, if it is requiring Doctrine DBAL and you don't want to install it now for any reason, you can try this:
<?php
// ...
Schema::table('users', function ($table) {
DB::statement('ALTER TABLE users MODIFY COLUMN name VARCHAR(50)');
});
There is an outstanding (open for multiple years and still being discussed) issue related to Doctrine DBAL (discussion here: https://github.com/laravel/framework/issues/1186).
The deceptive part of this issue is that a ->change() will fail if any column is of type enum (not just the column you are changing!)
If your table has an enum column, you need to revert to using an alter statement (note you don't need to wrap it in a Table::schema:
DB::statement('ALTER TABLE users MODIFY COLUMN name VARCHAR(50)')
Related
I want to change some table columns in Laravel from nullable to having a default value. I installed doctrine/dbal, and created a new migration with the following columns I want to change (previously nullable):
public function up()
{
Schema::table('movies', function (Blueprint $table) {
$table->string('movieDirector')->default('')->change();
$table->string('movieGenre')->default('')->change();
$table->string('movieCast')->default('')->change();
});
}
However this doesn't seem to have done anything. Is it possible to do? Thanks!
You need to create a new migration using command:
php artisan make:migration update_movies_table
Then, in that created migration class, add this line, using the change method like this :
public function up()
{
Schema::table('movies', function (Blueprint $table) {
$table->string('movieDirector')->default('test')->change();
$table->string('movieGenre')->default('test')->change();
$table->string('movieCast')->default('test')->change();
});
}
To make these changes and run the migration, use the command:
php artisan migrate
Scenario: I create a column name price which have lots of data and now I need to change that 'price' Column name to oldPrice without losing it's data and using migration.
Is there any way please let me know. Thanks
To do or undo any changes in migrations. You must write new migration this will not let you or your team mates lose any data and your app will not break.
To make change in column use following :
Make a migration
php artisan make:migration change_price_to_old_price --table=table_name
and use below code according to your requirements.
In up() function:
public function up(){
Schema::table('table_name', function (Blueprint $table) {
$table->renameColumn('old_name', 'new_name');
});
}
In down() function just undo what you did in up()
public function down(){
Schema::table('table_name', function (Blueprint $table) {
$table->renameColumn('new_name', 'old_name');
});
}
Recommendation:
Always write down migration to undo what you are doing in your up function.
php artisan migrate:status to see which migrations have ran and which are remaining.
hit php artisan migrate: and see list of commands and learn about them
I want to change my two table name in the Laravel, so do I have to manually change the table name or it can be possible through migration.
from the docs laravel.com/docs/5.1/migrations#renaming-and-dropping-tables
To change a table name, you can do this:
Schema::rename($currentTableName, $newTableName);
You can use the drop or dropIfExists methods to remove an existing table:
Schema::drop('users');
Schema::dropIfExists('users');
Just add that to a migration and it should work.
You can rename table like that
Schema::rename('old_table', 'new_table');
BUT be careful if you have foreign keys, indexes and unique-s.
you will not be able to deleted them after renaming, like thiat
Schema::table('new_table', function (Blueprint $table) {
$table->dropForeign(['transaction_id']);
});
because they will have old names and these names have table name in them.
Thus, I recommend deleting foreign keys and other stuff first
Schema::table('old_table', function (Blueprint $table) {
$table->dropForeign(['transaction_id']);
});
Schema::rename('old_table', 'new_table');
Schema::table('new_table', function (Blueprint $table) {
$table->foreign('transaction_id')->references('id')->on('transactions');
});
Firstly, use CLI command to create a migration:
php artisan make:migration rename_table
Now, in the up method of the new migration class, use the rename method to change table name:
Schema::rename('old_table_name', 'new_table_name');
Next, execute the migration command:
php artisan migrate
To rename an existing database table, use the rename method:
Schema::rename($from, $to);
To drop an existing table, you may use the drop or dropIfExists methods:
Schema::drop('users');
Schema::dropIfExists('users');
Firstly, run this in your terminal to create a migration file to rename a table:
php artisan make:migration rename_old_name_to_new_name_table
Then in the up method, you should have this:
public function up()
{
Schema::rename('old_table_name', 'new_table_name');
}
Then in the down method, you should have this in case you want to revert previous changes made:
public function down()
{
Schema::rename('new_table_name', 'old_table_name');
}
When you create a new column in a table you can use the ->after('column name') to dictate where it goes. How can I create a migration that re-orders the columns in the right order I want?
Try this, hope it help you to find right solution:
public function up()
{
DB::statement("ALTER TABLE example MODIFY COLUMN foo DATE AFTER bar");
}
public function down()
{
DB::statement("ALTER TABLE example MODIFY COLUMN foo DATE AFTER bar");
}
If you want to do it without destroying data, you could migrate the data across at the same time you do the schema update:
use DB;
public function up()
{
//Give the moving column a temporary name:
Schema::table('users', function($table)
{
$table->renameColumn('name', 'name_old');
});
//Add a new column with the regular name:
Schema::table('users', function(Blueprint $table)
{
$table->string('name')->after('city');
});
//Copy the data across to the new column:
DB::table('users')->update([
'name' => DB::raw('name_old')
]);
//Remove the old column:
Schema::table('users', function(Blueprint $table)
{
$table->dropColumn('name_old');
});
}
I would suggest a DB::query('.. raw sql query ..'); and use the query from the answer "How to move columns in a MySQL table?"
Try this
public function up()
{
DB::statement("ALTER TABLE example CHANGE foo foo DATA_TYPE DATA_ATTRIBUTE(s) AFTER bar");
DB::statement("ALTER TABLE example CHANGE foo foo INT(10) UNSIGNED NOT NULL AFTER bar");
}
Alternatively if you too lazy to figure out the SQL, you can visit your phpMyAdmin, click your database, click your table, click the Structure tab, besides the column you want to move, click the change button, edit the last Move column column, click the Save button & then copy the SQL.
VERY IMPORTANT NOTE
Use the following solution only if you haven't launched your app yet (i.e. it's not yet used by any real users) as the following solution will delete the column and all data stored in it and will create a new empty column with the same name after the column you determine.
Suppose your column name is address and you want to reorder its position so that it comes after another column called city, and your table name is employees.
In your terminal type the next command:
php artisan migrate:make reorganize_order_of_column_address --table=employees
You may only change reorganize_order_of_column_address and employees according to your needs, but keep the rest of the command as it is.
This will generate a migration file in app/database/migrations folder, open it and put your code inside the up() function like this:
public function up()
{
Schema::table('employees', function(Blueprint $table)
{
$table->dropColumn("address");
});
Schema::table('employees', function(Blueprint $table)
{
$table->string('address')->after("city");
});
}
In Laravel 4, when working with many-to-many relationships as described in the 4.2 docs, how can I actually get Laravel to create the pivot table for me?
Do I need to add something in my migrations for the two models that are involved? Do I need to manually create a migration for the pivot table? Or how does Laravel know to create the pivot table?
All I've done so far is add the belongsToMany information to the two respective models, i.e.
class User extends Eloquent
{
public function roles()
{
return $this->belongsToMany('Role');
}
}
However, that does not trigger creation of the pivot table. What step am I missing?
It appears as though the pivot table does need to be created manually (i.e. Laravel does not do this automatically). Here's how to do it:
1.) Create a new migration, using singular table names in alphabetical order (default):
php artisan make:migration create_alpha_beta_table --create --table=alpha_beta
2.) Inside the newly created migration, change the up function to:
public function up()
{
Schema::create('alpha_beta', function(Blueprint $table)
{
$table->increments('id');
$table->integer('alpha_id');
$table->integer('beta_id');
});
}
3.) Add the foreign key constraints, if desired.
(I haven't gotten to that bit, yet).
Now to seed, say, the alpha table, using keys from beta, you can do the following in your AlphaTableSeeder:
public function run()
{
DB::table('alpha')->delete();
Alpha::create( array(
'all' => 'all',
'your' => 'your',
'stuff' => 'stuff',
) )->beta()->attach( $idOfYourBeta );
}
I use Jeffrey Way's Laravel-4-Generators or Laravel-5-Generators-Extended.
then you can just use this artisan command:
php artisan generate:pivot table_one table_two
To expand on Ben's answer (I tried to edit it but reviewers said it added too much):
To add the foreign key constraints, make sure if alpha id is unsigned, alpha_id is also unsigned in the pivot table. This migration would run after (2) in Ben's answer since it alters the table created then.
public function up()
{
Schema::table('alpha_beta', function(Blueprint $table)
{
$table->foreign('alpha_id')->references('id')->on('alpha');
$table->foreign('beta_id')->references('id')->on('beta');
});
}
For Many to Many relationships you can create the Migration file of the Database manually like this:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateAccountTagTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('account_tag', function (Blueprint $table) {
// $table->timestamps(); // not required
// $table->softDeletes(); // not required
$table->integer('account_id')->unsigned();
$table->foreign('account_id')->references('id')->on('accounts');
$table->integer('tag_id')->unsigned()->nullable();
$table->foreign('tag_id')->references('id')->on('tags');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('account_tag');
}
}
Note: in case you have timestamps on the pivot table you must set withTimestamps on the relationship of both ends like this:
return $this->belongsToMany(\Mega\Modules\Account\Models\Tag::class)->withTimestamps();
.
return $this->belongsToMany(\Mega\Modules\Account\Models\Account::class)->withTimestamps();
Create new migration:
php artisan make:migration create_alpha_beta_table --create=alpha_beta
Inside the newly created migration:
public function up() {
Schema::create('alpha_beta', function(Blueprint $table) {
$table->increments('id');
$table->unsignedBigInteger('alpha_id');
$table->unsignedBigInteger('beta_id');
// foreign keys
$table->foreign('alpha_id')->references('id')->on('alphas');
$table->foreign('beta_id')->references('id')->on('betas');
});
}
for the latest Laravel's versions:
composer require --dev laracasts/generators
php artisan make:migration:pivot table1 table2
In addition to all the above answers
There is no need to have an AI index for a pivot table. Its uniquely defined by its touple (key1,key2).
The primary key should be the composition (key1,key2). The benefits are that the touples are unique and all queries are best optimized.
So here comes a real life example:
Schema::create('bill_user', function (Blueprint $table) {
// unsigned is needed for foreign key
$table->integer('user_id')->unsigned();
$table->integer('bill_id')->unsigned();
$table->primary(['user_id', 'bill_id']);
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade');
$table->foreign(bill_id')
->references('id')->on('bills')
->onDelete('cascade');
});
following the latest laravel conventions, the up method should be
public function up() {
Schema::create('country_timezone', function (Blueprint $table) {
$table->foreignId('country_id')->references('id')->on('countries');
$table->foreignId('timezone_id')->references('id')->on('timezones');
});
}
the simplest but modern way of writing pivot table migration, where the Country and Timezone are models with many-to-many relationship. And id and timestamps are not necessary to include but straightforward manner
in the older version, you can use some generator or artisan to make pivots,
but in the newer version, this work is too easy.
you must only make migration to do that like the below code.
php artisan make:migration category_post --create=category_post
after run code
make migration with this params
$table->foreignId('post_id')->constrained('post');
$table->foreignId('category_id')->constrained('category');