How to add new column to existing table in laravel - php

I am adding new column name title in my table tasks. But I am getting an error that this column does not exist in that table. Can anybody help me to resolve that error. Here is my code:
php artisan make:migration add_title_to_tasks_table --table="tasks" and then added this code
Schema::table('tasks', function (Blueprint $table) {
$table->string('title');
});
to new table file created

To Alter table and add column.
/**
* Run the migrations.
*
* #return void
*/
public function up() {
Schema::table('tasks', function (Blueprint $table) {
$table->string('title')->after('id');
// to change column datatype or change it to `nullable`
// or set default values , this is just example
$table->string('title')->default('Test')->change();
});
}
You can refere documentation here, Laravel Migration

For those who are new to laravel and looking for a solution, please follow the steps
1). php artisan make:migration add_title_to_tasks_table --table="tasks"
2). Edit the newly created file in the migrations folder and add the below.
public function up() {
Schema::table('tasks', function (Blueprint $table) {
$table->string('title')->after('id');
// to change column datatype or change it to `nullable`
// or set default values , this is just example
$table->string('title')->default('Test')->change();
});
}
3). Run the migrations command.
php artisan migrate

Do the following:
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('tasks', function (Blueprint $table) {
$table->string('title')->after('your-column-name');
});
}
Replace 'your-column-name' with your existing column name.
Save the file. From terminal, execute:
php artisan migrate
The above command will add the column to your table.
You are getting that error because you are not running the migrate command.
Whenever you create a migration file, you must execute the above command in order to see the changes in your database table.
Also, if the new column does not exist in the models $fillable property, you will have to add it there as well..
/**
* The attributes that are mass assignable.
*
* #return array
*/
protected $fillable = [
'title', // <-- new column name
// .. other column names
];
Failing to do update the $fillable property will result in MassAssignmentExecption
Hope this helps you out. Happy Coding. Cheers.

Related

How can I modify DB structure in Laravel without truncating tables?

I have defined a DB table structure below.
If I want to modify a table column:
From
$table->string('active',1);
To:
$table->string('active',1)->nullable(); // allow null values
Every time I run the migration script, my tables will be truncated.
Is there a way to define a table structure and have it be modified to correct structure WITHOUT dropping the table?
Here is my code for now:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class VTUser extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('Z_user', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('nickname')->unique();
$table->string('email')->unique();
$table->string('passhash');
$table->string('keygen');
$table->string('active',1)->nullable();
$table->string('banned',1);
$table->string('admin',1);
$table->string('step',1);
// $table->rememberToken();
// $table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('Z_user');
}
}
There can be two ways of achieving this -
Either you can rollback the migration with php artisan migrate:rollback --step=1 and then change the up function with $table->string('active',1)->nullable();
Create a new migration to update the table by doing $table->string('active',1)->nullable(); in this new migration.

when using php artisan migrate, change table name in migration, error occur when using tinker to save object

This is my migration, I m using mysql, and when I run the migration, it success and I look at my mysql DB, the table's name is "receivedDocument" as I wanted.
class CreateReceivedDocumentsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('received_documents', function (Blueprint $table) {
$table->id();
$table->dateTime('receivedDate')->nullable();
$table->string('subjectDescription')->nullable();
$table->string('fromEntity')->nullable();
$table->string('documentNumber')->nullable();
$table->integer('documentTypeId')->nullable();
$table->dateTime('documentDate')->nullable();
$table->integer('responseTypeId')->nullable();
$table->text('remarks')->nullable();
$table->timestamps();
});
Schema::rename('received_documents', 'receivedDocument');
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::rename('receivedDocument', 'received_documents');
Schema::dropIfExists('received_documents');
}
}
And when I use tinker to create and save a record, it fails. Tinker doesn't seems to know I have change the table name in my migration.
>>> $rd = new \App\ReceivedDocument();
=> App\ReceivedDocument {#3036}
>>> $rd->subjectDescription = 'description sample';
=> "description sample"
>>> $rd->documentNumber = '1234/2020';
=> "1234/2020"
>>> $rd->save();
Illuminate/Database/QueryException with message 'SQLSTATE[42S02]: Base table or
view not found: 1146 Table 'dossier.received_documents' doesn't exist (SQL: inse
rt into `received_documents` (`subjectDescription`, `documentNumber`, `updated_a
t`, `created_at`) values (description sample, 1234/2020, 2020-06-11 10:18:00, 20
20-06-11 10:18:00))'
How can I tell tinker what I have change in my migration?
In your model, define table as following:
protected $table = 'receivedDocument';

How to drop schema with connection to table in another database?

In my Laravel app, I have connections to different databases and when I need to fresh my tables in each of database with a new dummy data (I do it with php artisan migrate:fresh --seed command) I always have this error
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'table_name' already exists
which is weird because I have down() method in my migration class
class CreateExampleTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::connection('conn2')->create('table_name', function (Blueprint $table) {
$table->bigIncrements('id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::connection('conn2')->dropIfExists('table_name');
}
}
If you use migrate:refresh instead of fresh it will rollback the database using your down() methods.
I think the problem is not in your down() but with your up() : it is trying to create a table, but a table with that name already exists.
I would suggest doing something like:
if (!Schema::hasTable('tbl_name')) {
// create table
}
You may also have to specify which database you are using in the migrations.

How do I add default value as same from another column in Laravel Migration

I have a questions table in my database, in which I have a column of question_title, now I have added a column question_slug, which will contain the question's slug URL, so how I set question_slug default value as question_title in Laravel Migration, I need this all because I have questions saved in the database so I have run php artisan make:migration add_column_to_questions --table=questions now I have this code:
Schema::table('questions', function (Blueprint $table) {
$table->string('question_slug')->default();
});
first of all, create a new migration and put this code within it:
connections_string : it's within web/config/database.php file
configuration
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class NameOfUrMigration extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('questions', function (Blueprint $table) {
$table->string('question_slug')->default();
});
$questions = DB::connection('connections_string')->table('questions')->get();
foreach($questions as $question)
{
$question->question_slug = str_slug($question->question_title);
$question->save();
}
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
//
}
}
According to the documentation, default() is used to Declare a default value for a column.
That means the value that gets inserted by default in a field if you do not provide a value for it in the insert query.
The default() cannot help you achieve what you need here.
What you could do is create a new migration class with a raw query in the up() method which will update the value of question_slug with the value of question_title.
something like this:
public function up()
{
$sql = "UPDATE `questions` SET `question_slug` = `question_title` WHERE 1;";
//add filtering conditions if you don't want ALL records updated
DB::connection()->getPdo()->exec($sql);
}
Make sure you also create a corresponding down() method for the rollback

Updating Existing Column Attributes - Laravel 5 Migration

I have
a existing column called cpe_mac. I created it via migration like this :
$table->string('cpe_mac')->default(NULL)->nullable();
I want
I want to add this ->unique() to that column, without having to drop it and re-add.
I've tried
$table->string('cpe_mac')->unique();
Migration File
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AlterCaptivePortalTable212017 extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('captive_portals', function (Blueprint $table) {
$table->string('cpe_mac')->unique();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('captive_portals', function (Blueprint $table) {
$table->string('cpe_mac')->default(NULL)->nullable();
});
}
}
I kept
getting
SQLSTATE[42701]: Duplicate column: 7 ERROR: column "cpe_mac" of relation "captive_portals" already exists
Is there a way to achieve this without having to drop my existing column? I have a lot client data that can't be deleted.
Schema::table('users', function (Blueprint $table) {
$table->string('cpe_mac')->unique()->change();
});
https://laravel.com/docs/5.0/schema#changing-columns
You need to use change() method:
Schema::table('captive_portals', function (Blueprint $table) {
$table->string('cpe_mac')->unique()->change();
});
Alternatively, you may create the index after defining the column. For example:
$table->unique('email');
https://laravel.com/docs/5.4/migrations#indexes
I had the same issue and this is the solution for Laravel 5.6:
Step1: run this command: composer require doctrine/dbal
step2:run this command:php artisan make:migration THE
-NAME_YOU_WANT --table=TABLENAME
step3: in the added migration, add $table->string('cpe_mac')->unique()->change(); in Schema::table part.
step4: run this command: php artisan migrate
If the column is already defined you can use:
$table->unique('cpe_mac');

Categories