PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label laravel-migrations. Show all posts
Showing posts with label laravel-migrations. Show all posts

Wednesday, November 16, 2022

[FIXED] How to clone Laravel migration fields into another migration?

 November 16, 2022     laravel, laravel-6, laravel-migrations     No comments   

Issue

I have this Laravel migration structure:

class CreateWarehouseProductTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('warehouse_products', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('product_id')->default(0);
            $table->integer('warehouse_id');
            $table->integer('free_amount')->default(0);
            $table->integer('booked_amount')->default(0);
            // ...
            $table->timestamps();
        });
    }

    // ...
}

I need to create a daily backup from warehouse products and for this I need to create a new table what is exactly same as warehouse_products and contains one more extra field for the backup's date.

Is there any best practice to do this? I think something like this:

class CreateWarehouseProductBackupTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('warehouse_product_backups', function (Blueprint $table) {
            CreateWarehouseProductTable->cloneFieldsToHere();
            $table->date('date_of_backup');
        });
    }
}

Is there something similar good practice to clone fields from an existing migration?


Solution

I found a solution, I think not elegant, but it's working:

class CreateWarehouseProductTable extends Migration
{
    public function up()
    {
        Schema::create('warehouse_products', function (Blueprint $table) {
            $this->setWarehouseProductColumns($table);
        });

        Schema::create('warehouse_product_backups', function (Blueprint $table) {
            $this->setWarehouseProductColumns($table);
            $table->date('date_of_backup')->nullable();
        });
    }

    public function setWarehouseProductColumns(Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('product_id')->default(0);
            $table->integer('warehouse_id');
            $table->integer('free_amount')->default(0);
            $table->integer('booked_amount')->default(0);
            // ...
            $table->timestamps();
    }
}


Answered By - netdjw
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, August 24, 2022

[FIXED] How to make a migration in laravel module?

 August 24, 2022     eloquent, laravel, laravel-migrations, module     No comments   

Issue

In my Laravel project, I use nwidart package for making modules. Now I want to add deleted_at column to an existing model. I should make a new migration in my module. How can I do this?

Here is the package documentation: https://nwidart.com/laravel-modules/v4/advanced-tools/artisan-commands

I want some thing like this for module:

php artisan make:migration add_soft_deletes_to_user_table --table="users"


Solution

Try this command: php artisan module:make-migration add_soft_deletes_to_users_table <ModuleName>.

Then do not forget to use Illuminate\Database\Eloquent\SoftDeletes trait on your User model.

use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Model {

use SoftDeletes;

}


Answered By - Majid Alaeinia
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, May 16, 2022

[FIXED] How to use variables instead of column names for running new Migrations directly in the Controller

 May 16, 2022     laravel, laravel-8, laravel-migrations, laravel-schema-builder, php     No comments   

Issue

I'm using Laravel 8 and I wanted to run this code which insert two new columns, if the attribute name does not exist in the returned results of product_attr_info_correction column names.

    $allAttrs = Attribute::all();
    $columns = Schema::getColumnListing('product_attr_info_correction'); 

    for($i=0;$i<count($allAttrs);$i++){
        foreach($columns as $column){
            if(!empty($allAttrs[$i]->name)){
                if(str_contains($column,$allAttrs[$i]->name)){
                    continue;
                }else{
                    $columnName = "product_".$allAttrs[$i]->name."_attr_correction";
                    $columnName2 = "product_".$allAttrs[$i]->name."_attr_rejecting_reason";
                    
                    Schema::table('product_attr_info_correction', function($table)
                    {
                        global $columnName;
                        global $columnName2;
                        
                        $table->tinyInteger($columnName)->default(1)->comment('confirmed = 1 , not confirmed = 0')->after('product_id');
                        $table->string($columnName2)->nullable()->after($columnName);
                    });
                    dd(1);
                }
            }else{
                continue;
            }
        }
    } 

Now it works fine and clean except the database column creation part which returns this error:

SQLSTATE[42000]: Syntax error or access violation: 1166 Incorrect column name '' (SQL: alter table product_attr_info_correction add tinyint not null default '1' comment 'confirmed = 1 , not confirmed = 0' after `product_id`, add varchar(255) null)

However if I replace $table->tinyInteger($columnName)->... with $table->tinyInteger('column_name_example')->..., it works correctly and create a new column.

This means that the variable $columnName & $columnName2 can not be called here somehow.

So I would really appreciate if you tell me how to call a variable instead of a particular name as column name when we want to insert a new one directly in the Controller?


Solution

global $columnName;
global $columnName2;

The above line won't work since they are those variables which are available globally and doesn't reside inside a namespace. The above line made PHP to check inside global namespace and didn't find anything as such. Hence, you got that SQL error where the value of the injected variables went blank or NULL.

To fix this, you can inject these variables in that function callback itself using use keyword like below:

function($table) use($columnName, $columnName2){


Answered By - nice_dev
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, April 19, 2022

[FIXED] How to change the foreign key reference table with Migration

 April 19, 2022     laravel, laravel-8, laravel-migrations, mysql, php     No comments   

Issue

I had migrated a migration in Laravel which was like this:

$table->unsignedBigInteger('rel_seller_id')->nullable();
$table->foreign('rel_seller_id')->references('id')->on('seller');

Now I need to change the seller table to sellers table.

But don't know how to do this with Migration!

So if you know, let me know please...


Solution

Just create a new migration.

...
public function up()
{
    Schema::table('table_name', function (Blueprint $table) {
        $table->dropForeign(['rel_seller_id']);

        $table->foreign('rel_seller_id')
            ->references('id')
            ->on('sellers');
    });
}
...

It will drop old foreign key and create a new one.



Answered By - S N Sharma
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, April 18, 2022

[FIXED] how to create laravel migration for postgresql array data type

 April 18, 2022     laravel, laravel-migrations, postgresql     No comments   

Issue

I have the following laravel migration up method

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('email')->unique();
        $table->string('mobile')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        // $table->string('sports');
        $table->date('dob');
        $table->string('height');
        $table->rememberToken();
        $table->timestamps();
    });

    DB::statement('ALTER TABLE users ADD COLUMN sports TYPE text[] AFTER password');
}

when I run migration it will show SQLSTATE[42601]: Syntax error: 7 ERROR: syntax error at or near "text" LINE 1: ALTER TABLE users ADD COLUMN sports TYPE text[] AFTER passwo... ^ (SQL: ALTER TABLE users ADD COLUMN sports TYPE text[] AFTER password). I don't know what's a problem there?


Solution

please try your Sql statement like this:

 DB::statement('alter table users alter sports drop default');
    DB::statement('alter table users alter sports type text[] using array[sports]');
    DB::statement("alter table users alter sports set default '{}'");


Answered By - OMR
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, April 13, 2022

[FIXED] How to add new column after a custom column existing at the DB

 April 13, 2022     laravel, laravel-8, laravel-migrations, migration, php     No comments   

Issue

I want to add new Column with Migration after a custom column, for example I have this table structure:

Table

Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to change column length of existing table in SQL?

 April 13, 2022     laravel, laravel-migrations, migration     No comments   

Issue

I have one SQL table which will contain (TEXT/VARCHAR) columns of some length.

How can I change the existing column length without dropping or hardcode existing database

Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] why foreign key not get setted in laravel migrations

 April 13, 2022     laravel, laravel-migrations, migration, model-view-controller     No comments   

Issue

I made an exam-question relationship, every exam has less than 200 questions, but when I run migrations, I go to the PHPMyAdmin and I don't find the foreign key set, it's only a

Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, March 11, 2022

[FIXED] Drop Unique Index Laravel

 March 11, 2022     laravel, laravel-5, laravel-migrations, php     No comments   

Issue

I kept getting this while run php artisan migrate

SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'email'; check that column/key exists

While I see that email is exist on my database.

enter image description here


My migration script. I was trying to drop the unique constraint.

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AlterGuestsTable3 extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('guests', function(Blueprint $table)
        {
            $table->dropUnique('email');

        });

    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('guests', function(Blueprint $table)
        {

            $table->dropUnique('email');

        });
    }

}

Did I forget to clear any caches ?

Any hints for me ?


Solution

When dropping indexes, Laravel will expect that the full name of the index be given.

You can check your database for the full name of the index, but if the key was generated by a previous Laravel migration, its name should conform to a single, simple naming convention.

Here is what the documentation has to say about its naming convention (as of v5.2):

By default, Laravel automatically assigns a reasonable name to the indexes. Simply concatenate the table name, the name of the indexed column, and the index type.

My guess is this is why you are getting an error. There is no email index, but there probably is a guests_email_unique index.

Give this migration a shot:

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AlterGuestsTable3 extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('guests', function(Blueprint $table)
        {
            $table->dropUnique('guests_email_unique');

        });

    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('guests', function(Blueprint $table)
        {
            //Put the index back when the migration is rolled back
            $table->unique('email');

        });
    }

}

I understand it is a little confusing that when creating an index you specify the column names, but when dropping the index later you need to supply the index's full name.

Please note that I've adjusted the down() method as well, so that it reverts dropping the unique index by adding it back.



Answered By - stratedge
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, February 20, 2022

[FIXED] How to let ID autoincrement start from certain number in Laravel Migration

 February 20, 2022     database-migration, eloquent, laravel, laravel-migrations     No comments   

Issue

I want to write a Laravel Migration auto increment ID as a primary key. I want to start this ID with a another value rather than 1. How can I do so ?

The migration up() function:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('phone');
        $table->rememberToken();
        $table->timestamps();
    });
}

Solution

add a record with id (desired id -1) and then delete it.

If you add a record with id 999, and then delete it, next record will have id 1000. You can also use SQL identity on your database



Answered By - Filip
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, February 10, 2022

[FIXED] PDOException (1044) SQLSTATE[HY000] [1044] Access denied for user ''@'localhost' to database 'forge'

 February 10, 2022     database-migration, laravel, laravel-5, laravel-migrations     No comments   

Issue

I am using Laravel 5 and getting the following exception:

PDOException (1044) SQLSTATE[HY000] [1044] Access denied for user ''@'localhost' to database 'forge'

My database configuration file is:

<?php

return [
/*
|--------------------------------------------------------------------------
| PDO Fetch Style
|--------------------------------------------------------------------------
|
| By default, database results will be returned as instances of the PHP
| stdClass object; however, you may desire to retrieve records in an
| array format for simplicity. Here you can tweak the fetch style.
|
*/

'fetch' => PDO::FETCH_CLASS,

/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for all database work. Of course
| you may use many connections at once using the Database library.
|
*/

'default' => 'mysql',

/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Here are each of the database connections setup for your application.
| Of course, examples of configuring each database platform that is
| supported by Laravel is shown below to make development simple.
|
|
| All database work in Laravel is done through the PHP PDO facilities
| so make sure you have the driver for your particular database of
| choice installed on your machine before you begin development.
|
*/

'connections' => [

    'sqlite' => [
        'driver'   => 'sqlite',
        'database' => storage_path().'/database.sqlite',
        'prefix'   => '',
    ],

    'mysql' => [
        'driver'    => 'mysql',
        'host'      => env('DB_HOST', 'localhost'),
        'database'  => env('DB_DATABASE', 'forge'),
        'username'  => env('DB_USERNAME', 'forge'),
        'password'  => env('DB_PASSWORD', ''),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],

    'pgsql' => [
        'driver'   => 'pgsql',
        'host'     => env('DB_HOST', 'localhost'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'charset'  => 'utf8',
        'prefix'   => '',
        'schema'   => 'public',
    ],

    'sqlsrv' => [
        'driver'   => 'sqlsrv',
        'host'     => env('DB_HOST', 'localhost'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'prefix'   => '',
    ],

],

/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk haven't actually been run in the database.
|
*/

'migrations' => 'migrations',

/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer set of commands than a typical key-value systems
| such as APC or Memcached. Laravel makes it easy to dig right in.
|
*/

'redis' => [

    'cluster' => false,

    'default' => [
        'host'     => '127.0.0.1',
        'port'     => 6379,
        'database' => 0,
    ],

    ],

];

How can I solve it?


Solution

Put a .env file in your root directory and paste this code there.

APP_ENV=local
APP_DEBUG=true
APP_KEY=1CaND3OKKvOGSBAlCg6IyrRmTQWwZjOO

DB_HOST = localhost
DB_DATABASE = YOUR_DATABASE_NAME
DB_USERNAME = USER_NAME
DB_PASSWORD = PASSWORD

CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null

Update your database, username and password field here and it should solve your problem. In your configuration file env() function is looking for this file and variables from here.

UPDATE: You must create a blank database before running the app or migration.



Answered By - Ariful Haque
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, February 3, 2022

[FIXED] Laravel 5.4: SQLSTATE[HY000]: General error: 1005 Can't create table "Foreign key constraint is incorrectly formed"

 February 03, 2022     laravel, laravel-5, laravel-migrations, mysql, php     No comments   

Issue

I'm using Laravel 5.4 and I have added this Migration:

public function up()
    {
        Schema::create('episodes', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('course_id')->unsigned();
            $table->foreign('course_id')->references('id')->on('courses')->onDelete('cascade');
            $table->string('type', 10);
            $table->string('title');
            $table->string('slug');
            $table->text('description');
            $table->text('body');
            $table->string('videoUrl');
            $table->string('tags');
            $table->string('time', 15)->default('00:00:00');
            $table->integer('number');
            $table->integer('viewCount')->default(0);
            $table->integer('commentCount')->default(0);
            $table->integer('downloadCount')->default(0);
            $table->timestamps();
        });
    }

Now when I run php artisan migrate, I get this error:

SQLSTATE[HY000]: General error: 1005 Can't create table elearning.episodes (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table episodes add constraint episodes_course_id_foreign foreign key (course_id) references courses (id) on delete cascade)

I also tried this but still gets the same error:

$table->unsignedBigInteger('course_id');

So how can I properly run this Migration? I'm really stuck with this, please help me out...


USERS MIGRATTION:

Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('level')->default('user');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });

Course Migration:

Schema::create('courses', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->string('type', 10);
            $table->string('title');
            $table->string('slug');
            $table->text('description');
            $table->text('body');
            $table->string('price',50);
            $table->string('imageUrl');
            $table->string('tags');
            $table->string('time', 15)->default('00:00:00');
            $table->integer('viewCount')->default(0);
            $table->integer('commentCount')->default(0);
            $table->timestamps();
        });

Solution

Rather than use :

$table->increments('id');

you should use :

$table->id();

(it's just easier).

To create your foreign relationships, rather than have

$table->integer('course_id')->unsigned();
$table->foreign('course_id')->references('id')->on('courses')->onDelete('cascade');

you can just use :

$table->foreignId('course_id')->constrained()->cascadeOnDelete();

which will automatically create a column of the right type (unsigned big integer) and then create the relationship by looking for the id column on the courses table.

EDIT

As you're using an older version of Laravel, you cannot use the id() function, so just create the course_id column as a big integer :

$table->bigInteger('course_id')->unsigned();

and then create your relationship as before.



Answered By - Giles Bennett
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, January 28, 2022

[FIXED] Laravel insert default value instead of data sent via request

 January 28, 2022     laravel, laravel-migrations     No comments   

Issue

I'm facing a peculiar issue on my Laravel app that when I insert data to the database, it always inserts the default value instead of the data sent via a post request. So I dd() the value before inserting them into the database and the correct data showing. But on the database, it always inserts the default value in the migration file.

The same code works fine for another modal.

HTML form

<div class="form-row">
    <div class="col-md-6 mb-3">
        <label for="is_free">Is Free</label>
        <select class="form-control" name="is_free" required>
            <option value="1">Free</option>
            <option value="0">Pro Only</option>
        </select>
        @error('is_free')
        <div class="text-danger mt-2 small ">{{ $message }}</div>
        @enderror
    </div>
</div>

Migration

public function up()
{
    Schema::create('chapters', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->string('slug');
        $table->string('description');
        $table->mediumText('content');
        $table->tinyInteger('is_free')->default(1);
        $table->timestamps();
    });
}

Controller

Chapter::create([
    'title' => $request->title,
    'slug' => $request->slug,
    'description' => $request->description,
    'content' => $request->content,
    'is_free' => $request->is_free,
]);

Solution

in your Chapter Model, make sure you have $fillable property with correct properties:

class Chapter extends Model
{
 protected $fillable = ['title','slug','description','content','is_free'];
....
}


Answered By - OMR
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, January 21, 2022

[FIXED] Removing default migrations from Laravel

 January 21, 2022     composer-php, laravel, laravel-5, laravel-migrations     No comments   

Issue

After creating a new Laravel project with laravel new, there are a couple of migration files in the database > migrations folder:

2014_10_12_000000_create_users_table.php
2014_10_12_100000_create_password_resets_table.php

These seem to be examples of typically useful migrations and are probably a good place to start if you need a system that requires something similar. However I'd like to delete them so they don't clash with something in a new project I'm building.

I was hoping I would be just able to delete the files, as I've not run php artisan migrate yet, but when I try my IDE says:

enter image description here

Why are these files already tied into the system, and how can I safely remove them? Is there some documentation on the Laravel site that I've not been able to find about this?

I guess I could ignore the warning and try running composer dump-autoload -o, but is this really OK?


Solution

Why are these files already tied into the system

to map all project classes

how can I safely remove them?

Ignore IDE and delete them then run composer dump-autoload and will remap project classes

Is there some documentation on the Laravel site that I've not been able to find about this?

i don't see any thing about this in laravel documentation site



Answered By - Mortada Jafar
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, January 17, 2022

[FIXED] Laravel 2 instances of BadMethodCallException: 'int does not exist' and 'method does not exist'

 January 17, 2022     composer-php, laravel, laravel-migrations, php, terminal     No comments   

Issue

I am currently doing migrations in Laravel via the Terminal, and have these two errors when attempting to use php artisan migrate; I will print errors below:

 BadMethodCallException  : Method Illuminate\Database\Schema\Blueprint::int does not exist.

  at /Users/shaquilenoor/Desktop/chatapi/vendor/laravel/framework/src/Illuminate/Support/Traits/Macroable.php:100
     96|      */
     97|     public function __call($method, $parameters)
     98|     {
     99|         if (! static::hasMacro($method)) {
  > 100|             throw new BadMethodCallException(sprintf(
    101|                 'Method %s::%s does not exist.', static::class, $method
    102|             ));
    103|         }
    104| 

  Exception trace:

  1   Illuminate\Database\Schema\Blueprint::__call("int")
      /Users/shaquilenoor/Desktop/chatapi/database/migrations/2019_01_29_045824_create_contacts_table.php:15

  2   CreateContactsTable::{closure}(Object(Illuminate\Database\Schema\Blueprint))
      /Users/shaquilenoor/Desktop/chatapi/vendor/laravel/framework/src/Illuminate/Database/Schema/Builder.php:164

It seems both errors stem from my CreateContactsTable, so I will print the code from that file below:

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateContactsTable extends Migration
{
    public function up()
    {
        Schema::create('contacts', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('user1_id');
            $table->unsignedInteger('user2_id');
            $table->int('room_id')->unique();
            $table->timestamps();
            $table->foreign('room_id')->references('id')->on('rooms');
            $table->foreign('user1_id')->references('id')->on('users');
            $table->foreign('user2_id')->references('id')->on('users');
        });
    }

    public function down()
    {
        Schema::dropIfExists('contacts');
    }
}

Solution

Error is in line:

$table->int('room_id')->unique();

There is no int method. You should use integer instead:

$table->integer('room_id')->unique();


Answered By - Marcin NabiaƂek
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, January 13, 2022

[FIXED] Error: "SQLSTATE[42000]: Syntax error or access violation: 1064

 January 13, 2022     laravel, laravel-migrations, mysql     No comments   

Issue

I got a Laravel MySQL migration problem.

Migration:

 public function up()
{
    Schema::create('capsule_packages', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->tinyInteger('type')->unsigned();
        $table->json('data')->nullable();
        $table->decimal('price', 19, 4);
        $table->text('description')->nullable();
        $table->timestamps();
    });
}

Error:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'json null, price decimal(19, 4) not null, description text null, created_at' at line 1 (SQL: create tablecapsule_packages(idint unsigned not null auto_increment primary key,namevarchar(255) not null,typetinyint unsigned not null,datajson null,pricedecimal(19, 4) not null,descriptiontext null,created_attimestamp null,updated_at` timestamp null) default character set utf8 collate 'utf8_unicode_ci')


Solution

This is probably due to your MySQL version. Did some digging around, and seems like since Laravel 5.2, the $table->json() method will try to create an actual json field in the database. But, in your example, the json ins't available in your current MySQL version. You can use this field only from MySQL version 5.7.8. and higher. If you're using version that's lower than this, you can resolve this error by creating a text field, instead of json.

You can see this in you error code:

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near json

Source: dev.mysql.com/doc/relnotes/mysql/5.7/en/news-5-7-8.html#mysqld-5-7-8-json

EDIT:

As per MariaDB version 10.1.x and lower does not support json data type

Source: github.com/laravel/framework/issues/13622



Answered By - zlatan
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, January 8, 2022

[FIXED] General error: 1005 Can't create table (errno: 150 "Foreign key constraint is incorrectly formed")

 January 08, 2022     laravel, laravel-8, laravel-migrations, mysql, php     No comments   

Issue

I have a database Migration in Laravel 8 that goes like this:

class CreateArticlesTable extends Migration
{
    public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->id();
            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->string('title');
            $table->string('slug');
            $table->text('description');
            $table->text('body');
            $table->string('imageUrl');
            $table->string('tags');
            $table->integer('viewCount')->default(0);
            $table->integer('commentCount')->default(0);
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('articles');
    }
}

But whenever I want to run this, I get this error:

General error: 1005 Can't create table elearning.articles (errno: 150 "Foreign key constraint is incorrectly formed")

I don't what the heck is going wrong here, so if you know how to solve this issue, please let me know...


Solution

Instead of using:

$table->integer('user_id')->unsigned();

Use:

$table->unsignedBigInteger();

Laravel uses unsignedBigInteger which is 20 digits and unsignedInteger only takes 11 digits

https://laravel.com/docs/8.x/migrations#foreign-key-constraints



Answered By - S. Hossain
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, January 7, 2022

[FIXED] Postgres and Laravel how to change column from type string to integer?

 January 07, 2022     eloquent, laravel, laravel-migrations, php, postgresql     No comments   

Issue

I am trying to change a column from type string to integer on Postgres and Laravel 6.x. I've tried to do this with a migration like so:

    public function up()
    {
        Schema::table('job_listings', function (Blueprint $table) {
            $table->integer('company_id')->change();
        });
    }

When I run this migration I get an error that the column cannot be automatically cast to an integer:

In Connection.php line 664:

  SQLSTATE[42804]: Datatype mismatch: 7 ERROR:  column "company_id" cannot be cast automatically to type integer
  HINT:  You might need to specify "USING company_id::integer". (SQL: ALTER TABLE job_listings ALTER company_id TYPE INT)


In PDOStatement.php line 123:

  SQLSTATE[42804]: Datatype mismatch: 7 ERROR:  column "company_id" cannot be cast automatically to type integer
  HINT:  You might need to specify "USING company_id::integer".


In PDOStatement.php line 121:

  SQLSTATE[42804]: Datatype mismatch: 7 ERROR:  column "company_id" cannot be cast automatically to type integer
  HINT:  You might need to specify "USING company_id::integer".

How do we specify USING to change this column from type string to integer in PostgreSQL?


Solution

You must specify an explicit cast since there is no implicit (automatic) cast from text or varchar to integer. I don't know of a Laravel function to specify the cast so I would suggest you use raw DB statement to achieve this.

You could do this:

public function up()
{
    DB::statement('ALTER TABLE job_listings ALTER COLUMN 
                  company_id TYPE integer USING (company_id)::integer');
}

There can also be cases where there are whitespace in your text or varchar fields so you would have to trim before casting

public function up()
{
    DB::statement('ALTER TABLE job_listings ALTER COLUMN 
                  company_id TYPE integer USING (trim(company_id))::integer');
}


Answered By - Clement Sam
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, December 30, 2021

[FIXED] Laravel Add a new column to existing table in a migration

 December 30, 2021     laravel, laravel-migrations, php     No comments   

Issue

I can't figure out how to add a new column to my existing database table using the Laravel framework.

I tried to edit the migration file using...

<?php

public function up()
{
    Schema::create('users', function ($table) {
        $table->integer("paid");
    });
}

In terminal, I execute php artisan migrate:install and migrate.

How do I add new columns?


Solution

To create a migration, you may use the migrate:make command on the Artisan CLI. Use a specific name to avoid clashing with existing models

for Laravel 5+:

php artisan make:migration add_paid_to_users_table --table=users

for Laravel 3:

php artisan migrate:make add_paid_to_users

You then need to use the Schema::table() method (as you're accessing an existing table, not creating a new one). And you can add a column like this:

public function up()
{
    Schema::table('users', function($table) {
        $table->integer('paid');
    });
}

and don't forget to add the rollback option:

public function down()
{
    Schema::table('users', function($table) {
        $table->dropColumn('paid');
    });
}

Then you can run your migrations:

php artisan migrate

This is all well covered in the documentation for both Laravel 4 / Laravel 5:

  • Schema Builder
  • Migrations

And for Laravel 3:

  • Schema Builder
  • Migrations

Edit:

use $table->integer('paid')->after('whichever_column'); to add this field after specific column.



Answered By - Phill Sparks
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing