How can I add field using alter table on the migration laravel? - laravel

I use laravel 5.3
My migration like this :
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('api_token')->nullable();
$table->string('email',100)->unique();
$table->string('password')->nullable();
$table->string('avatar',100)->nullable();
$table->string('full_name',100)->nullable();
$table->date('birth_date')->nullable();
$table->smallInteger('gender')->nullable();
$table->timestamps();
$table->softDeletes();
});
}
public function down()
{
DB::statement('SET FOREIGN_KEY_CHECKS = 0');
Schema::dropIfExists('users');
DB::statement('SET FOREIGN_KEY_CHECKS = 1');
}
}
I want to add new field like this :
$table->string('mobile_number',20)->nullable();
But I don't want to add it on the schema. I want to use alter table
On my staging server and live server had set automatic migration
So if I use alter table, it will automatic migration. So on the table in database will automatic add mobile_number field if the code merge to development or master
If I add on the schema, it will not automatically migrate
How can I add the field using alter table?

You can use the schema to update an existing table. Create a new migration using the artisan command then add something like
Schema::table('users', function (Blueprint $table) {
$table->string('mobile_number',20)->nullable();
});
If you really wanted to do RAW sql you can do something like
DB::statement("ALTER TABLE users .....");
However the schema way is much better if you can get it to work

In the command line, execute artisan command to add new migration for your table:
php artisan make:migration add_mobile_number_to_users_table --table=users
Then you can put your code inside the newly created migration file:
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('mobile_number',20)->nullable();
}
}
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('mobile_number');
}
}

Related

Laravel 8 - Foreign key constraint is incorrectly formed

I don't know what's wrong because I'm very new to this.
// Product Model
class Product extends Model
{
use HasFactory;
public function store()
{
return $this->belongsTo(Store::class);
}
}
// Store Model
class Store extends Model
{
use HasFactory;
public function products()
{
return $this->hasMany(Product::class);
}
}
// Products table migration
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->float('price');
$table->string('description');
$table->timestamps();
$table->foreignId('store_id')->constrained()->onDelete('cascade');
});
// Stores table migration
Schema::create('stores', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('image_url');
$table->string('phone');
$table->timestamps();
});
When I run the migration, it gives me this error
I've tried changing the data type of the 'id' but still not working. I've also tried with
$table->foreign('store_id')->references('id')->on('stores')->onDelete('cascade');
but still not working.
What I want is a relation so that when I delete a store, all products that belong the store are also deleted.
Thanks 🙏
Change the name of the stores migration file to a date prior to 2021-07-28 so the table stores is migrated before the table products
Example: 2021_07_27_004700_create_stores_table
Laravel uses the name of the migration files for the order of migration. With the format of the date as the start of the file name, it is dependant on the date of the creation of the file.

How to make a timestamp column immutable in Laravel 7 migration?

I am working on a project and want to make a timestamp column in the database immutable. In Symfony, I know how to do that, but in Laravel, I don't understand.
class CreateUsersTable extends Migration
{
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('email')->unique();
$table->string('verification_code')->nullable();
$table->timestamp('accept_policy_at');
});
}
}

Base table or view not found error

ProductTable
public function up()
{
Schema::create('product', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('description');
$table->string('type');
$table->integer('size');
$table->integer('price');
$table->string('image')->nullable();
$table->timestamps();
});
}
When I hit submit, I got error saying base table not found
Laravel can not find the prular form of the table name that you used, just specify your table name on your model like so; And check your view aswell make sure on your resource/view you have a file named successs.blade.php
public $table = "yourTableName";
may be your table is not available in database so first add the table in
your database. in your model like this
public $table = "yourTableName";
after the define your table in your model just migrate the table in your database
php artisan make:migration

Removing column from database in Laravel 5+

I've a blog for which the articles table Schema is defined like this:
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('title');
$table->string('thumb')->nullable();
$table->text('excerpt');
$table->text('body');
$table->string('slug')->unique();
$table->integer('comment_count')->unsigned()->default(0);
$table->integer('view_count')->unsigned()->default(0);
$table->timestamps();
$table->softDeletes();
}
public function down()
{
Schema::drop('articles');
}
I want to drop the columns comment_count and view_count without losing existing data in the table
I defined a new migration like this:
class RemoveCommentViewCount extends Migration
{
public function up()
{
//nothing here
}
public function down()
{
Schema::table('articles', function($table) {
$table->dropColumn('comment_count');
$table->dropColumn('view_count');
});
}
}
and I did php artisan migrate . It did migrate successfully, but the two columns are not dropped.
What am I doing wrong? How can I drop those columns without losing the existing data in the table?
Your migration must look like this:
class RemoveCommentViewCount extends Migration
{
public function up()
{
Schema::table('articles', function($table) {
$table->dropColumn('comment_count');
$table->dropColumn('view_count');
});
}
public function down()
{
Schema::table('articles', function($table) {
$table->integer('comment_count');
$table->integer('view_count');
});
}
}
The dropColumn in the up method, because with new migration you want to delete this columns. If you make a rollback, you have another time the two columns
Even you can drop the multiple columns in a single line by passing the array column to dropColumn function.
class RemoveCommentViewCount extends Migration
{
public function up()
{
Schema::table('articles', function($table) {
$table->dropColumn(['comment_count', 'view_count']);
});
}
public function down()
{
Schema::table('articles', function($table) {
$table->integer('comment_count');
$table->integer('view_count');
});
}
}
In case you have a foreign key constraint, then drop first the foreign key index association and then can pass the column to dropColumn function with others like following.
public function up()
{
Schema::table('customer_orders', function($table) {
$table->dropForeign(['product_id']);
$table->dropForeign(['shipping_address_id']);
$table->dropColumn(['product_id', 'shipping_address_id', 'column1', 'column2']);
});
}
Create remove column migration
php artisan make:migration RemoveCommentViewCount
The down method is for rollbacks, so add dropColumn in your up() function and reverse in down()
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class RemoveCommentViewCount extends Migration
{
public function up()
{
if (Schema::hasColumn('comment_count', 'view_count')){
Schema::table('articles', function (Blueprint $table) {
$table->dropColumn('comment_count');
$table->dropColumn('view_count');
//OR
$table->dropColumn(['comment_count', 'view_count']);
});
}
}
public function down()
{
Schema::table('articles', function($table) {
$table->integer('comment_count');
$table->integer('view_count');
});
}
}
Check laravel documentation on dropping columns migrations
I had a similar issue, I edited the initial migration, that is the initial table schema, removed the columns and then run php artisan migrate:refresh and it worked for me
Just add this code into your down() function in migration.php file
Schema::table('articles', function (Blueprint $table) {
$table->integer('comment_count')->unsigned()->default(0);
$table->integer('view_count')->unsigned()->default(0);
});
and then run --> php artisan migrate:rollback

Laravel migrate database database using artisan with new columns

I am using laravel and I am trying to do another migration but the table already exists so it is throwing the following error:
[PDOException]
SQLSTATE[42S01]: Base table or view already
exists: 1050 Table 'users' already exists
I've added this line into the migration file:
$table->softDeletes();
This is the full file:
<?php
use Illuminate\Database\Migrations\Migration;
class ConfideSetupUsersTable extends Migration
{
/**
* Run the migrations.
*/
public function up()
{
// Creates the users table
Schema::create('users', function ($table) {
$table->increments('id');
$table->string('firstname');
$table->string('lastname');
$table->string('username')->unique();
$table->string('email')->unique();
$table->string('password');
$table->string('confirmation_code');
$table->string('remember_token')->nullable();
$table->softDeletes();
$table->boolean('confirmed')->default(false);
$table->timestamps();
});
// Creates password reminders table
Schema::create('password_reminders', function ($table) {
$table->string('email');
$table->string('token');
$table->timestamp('created_at');
});
}
/**
* Reverse the migrations.
*/
public function down()
{
Schema::drop('password_reminders');
Schema::drop('users');
}
}
Any ideas what I'm doing wrong?
You can rollback the migration and then run it again:
php artisan migrate:rollback
And then:
php artisan migrate
Attention in your case this will delete all data from the table since it will drop users and password reminder and then recreate it.
The alternative is to create a new migration:
php artisan migrate:make users_add_soft_deletes
Put this in there:
Schema::table('users', function ($table) {
$table->softDeletes();
});
And run php artisan migrate to apply the new migration

Resources