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
Related
I have a Laravel 5 application, and I am trying to limit the length of a database TEXT column up to 500.
I have it set as:
$table->text('excerpt');
How can I modify this so that it is limited to 500 characters?
Require Doctrine:
composer require doctrine/dbal
Create a new migration using string() instead of text():
public function up()
{
Schema::table('table_name', function (Blueprint $table) {
$table->string('excerpt', 500)->change();
});
}
Or you can use raw SQL:
public function up()
{
DB::statement('ALTER TABLE table_name MODIFY excerpt VARCHAR(500)');
}
And run the migrate command:
php artisan migrate
I am new to laravel and I want to know that can't we add two column into existing table using
php artisan make:migration
at once for Ex. if my users table contain id,user_name and now I want to add two new column like as user_phone and user_email in one
php artisan make:migration add_user_phone_to_users_table add_user_email_to_users_table
something like that ? I am very sorry If my question is wrong.. I can add new field one by one into two separate migration but want to know is it possible to add two new column to existing table at once. Thanks in advance and I hope I will get a satisfied answer.
You are right by creating a new migration, php artisan make:migration add_email_and_phone_number_to_users --table=users
In the migration you can add the code for this:
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('email')->nullable();
$table->string('phone_number')->nullable();
});
}
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn(['email', 'phone_number']);
});
}
when adding more columns to an existing table using another migration, you need to define the table
php artisan make:migration name_of_the_migration --table="table_name"
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');
}
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');