Drop and then create same columns in current up migration function - laravel

Schema::table('users', function (Blueprint $table) {
$table->dropTimestamps();
$table->dropColumn(['email', 'bio']);
$table->string('email', 20)->unique()->after('id');
$table->string('bio', 150)->after('surname');
$table->timestamps();
});
That is what I've got now. So, I have the columns existing atm in my table, but I want to modify and re-arrange them a bit. But when I run the migration, I get SQL error that email column exists. And I will probably get the same error for the bio and timestamps as well. I kind of understand why this happens, so what am I asking is just for a workaround.
Is it possible to make what I want inside one single migration, or I have to create a migration for deleting the columns and then a separate migration for creating them the way I want?

Just break the schema up into two calls
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->dropTimestamps();
$table->dropColumn(['email', 'bio']);
});
Schema::table('users', function (Blueprint $table) {
$table->string('email', 20)->unique()->after('id');
$table->string('bio', 150)->after('surname');
$table->timestamps();
});
}
This way the change is occurring in one migration with two database calls.

Consider that if you drop the columns, you will lose ALL THE DATA contained therein. Normally this is a very bad and dangerous idea. If you instead need to simply change parameters, you should use the change() function to make the required modifications to your schema. This will convert the existing data to the best of your databases's ability.
NEVER DROP COLUMNS on an in-use database unless you absolutely know what you're doing.
public function up()
{
Schema::table('users', function (Blueprint $table) {
// Add the unique constraint, for example
$table->string('email', 20)->unique()->after('id')->change();
// Add the length to the bio, for example
$table->string('bio', 150)->after('surname')->change();
});
}
public function down()
{
Schema::table('users', function (Blueprint $table) {
// Remove length and constraints
$table->string('email')->unique(false)->change();
$table->string('bio')->change();
});
}

Related

How to limit probable entry from user in migration?

What if I try to limit possible entries in migration level in Laravel. For instance i have a migration:
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('type')
$table->timestamps();
});
}
Now I want to accept anything from image, post, bio for the type column. if the user try to save anything except the 3 options, i want the DB to deny. How can I do so ?
You can use an enum column allowing only the defined values.
https://laravel.com/docs/8.x/migrations#column-method-enum
$table->enum('type', ['image', 'post', 'bio']);

Has Many Through where the middle table has both forain keys in laravel 5.6

I need to make a HasManyThough relation where the middle Model holds the foreign keys of both Models.
Here is detail:
Migrations:
Schema::create('carriers', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
});
Schema::create('shipping_zones', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
});
Schema::create('shipping_rates', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('shipping_zone_id')->unsigned()->index();
$table->integer('carrier_id')->unsigned()->index();
$table->decimal('rate', 20, 6);
});
Now I need something like
$carrier->shippingZone()
Is there any easy way to get this?
As per your migrations you need Many To Many relation rather than the HasManyThough relation.
Carrier.php
public function shippingZones()
{
return $this->belongsToMany('App\ShippingZone', 'shipping_rates);
}
You can access all shipping zones related to the carrier using, $carrier->shippingZones.
If you need to chain the query you can use $shippingZones = $carrier->shippingZones()->orderBy('id')->get(); here
If you need to use HasManyThough you would have to change the migrations. here

Constrains in Foreign keys using database migrations

i cant figure out what im doing wrong, but everything looks ok, is giving me this errroof
Foreign key constraint is incorrectly formed
on my migrations, but i dont see any issue.
Migration table 1:
public function up()
{
Schema::create('candidate_industries', function (Blueprint $table) {
$table->increments('id');
$table->integer('candidate_id')->unsigned();
$table->foreign('candidate_id')->references('id')->on('candidates');
$table->integer('industry_id')->unsigned();
$table->foreign('industry_id')->references('id')->on('industries');
});
}
Migration number 2:
public function up()
{
Schema::create('candidate_regions', function (Blueprint $table) {
$table->increments('id');
$table->integer('candidate_id')->unsigned();
$table->foreign('candidate_id')->references('id')->on('candidates');
$table->integer('region_id')->unsigned();
$table->foreign('region_id')->references('id')->on('regions');
});
}
The issue was because "candidates" id column had a different dataType set, in my case was BigInt when i was trying to create a relation with a column of int.

Review Schedule Task Code In Laravel 5.1

I am writing a code to be scheduled to run occasionally. I want to remove records of users who have their details on the users table but does not have their records in the profiles table as well. I am thinking about removing the by their id, but I am not sure how I can make the match. profiles migration:
public function up()
{
Schema::create('profiles', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('gender',5);
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); // When a profile is deleted- his corresponding associated id details are deleted as well.
$table->tinyInteger('age')->unsigned()->nullable();
$table->string('goals')->nullable();;
$table->string('activityType')->nullable();
$table->rememberToken(); // for remember me feature.
});
}
Users migration:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('username',20)->unique();
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
I have started to write the query, yet I am not sure how to proceed.
public function handle()
{
// type the query to get users that have no data in their profiles.
$empty_profile=App\Profile:::where('id','')->get;
$user_id=App\User::where('id')
}
Appreciate your help. Thanks.
Although your example is not exactly clear to me (and I wonder why there would be users without profiles in the first place?) I think this is what you need:
public function handle()
{
$empty_profiles = App\User::doesntHave('profile')->delete();
}
This will work if the models are correctly connected see also:
https://laravel.com/docs/master/eloquent-relationships

laravel migration best way to add foreign key

Simple question: I'm new to Laravel. I have this migration file:
Schema::create('lists', function(Blueprint $table) {
$table->increments('id');
$table->string('title', 255);
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
I want to update it to add onDelete('cascade').
What's the best way to do this?
Firstly you have to make your user_id field an index:
$table->index('user_id');
After that you can create a foreign key with an action on cascade:
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
If you want to do that with a new migration, you have to remove the index and foreign key firstly and do everything from scratch.
On down() function you have to do this and then on up() do what I've wrote above:
$table->dropForeign('lists_user_id_foreign');
$table->dropIndex('lists_user_id_index');
$table->dropColumn('user_id');
In Laravel 7 it can be done in one line
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
let's say you have two tables student and section , you can refer the following two table structure for adding foreign key and making onDelete('cascade') .
Table -1 :
public function up()
{
Schema::create('student', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('address');
$table->string('phone');
$table->string('about')->nullable();
$table->timestamps();
});
}
Table - 2:
public function up()
{
Schema::create('section', function (Blueprint $table) {
$table->id();
$table->bigInteger('student_id')->unsigned()->index()->nullable();
$table->foreign('student_id')->references('id')->on('student')->onDelete('cascade');
$table->string('section')->nullable();
$table->string('stream')->nulable();
$table->timestamps();
});
}
hope it will help you -:)
you can read the full article from here .
Schema::create('roles',function(Blueprint $table){
$table->bigIncrements('id');
$table->string('name');
$table->timestamps();
});
Schema::create('permissions',function(Blueprint $table){
$table->unsignedBigInteger('role_id');
$table->foreign('role_id')->references('id')->on('roles');
$table->string('permission');
});
As of Laravel 8:
$table->foreignIdFor(OtherClass::class)->constrained();
So simple :)
Make sure that the OtherClass migration file is running EARLIER (by filename date as usual).
If the OtherClass id is not autoincrementing, the otherclass_id would have a type of char instead of bigint, in which case->
Use this instead:
$table->foreignId('otherclass_id')->index()->constrained()->cascadeOnDelete();
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
In this example, we are stating that the user_id column references the id column on the users table. Make sure to create the foreign key column first! The user_id column is declared unsigned because it cannot have negative value.
You may also specify options for the "on delete" and "on update" actions of the constraint:
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade');
To drop a foreign key, you may use the dropForeign method. A similar naming convention is used for foreign keys as is used for other indexes:
$table->dropForeign('posts_user_id_foreign');
If you are fairly new to Laravel and Eloquent, try out the Laravel From Scratch series available on laracasts. It is a great guide for beginners.
Laravel 7.x Foreign Key Constraints
Laravel also provides support for creating foreign key constraints, which are used to force referential integrity at the database level. For example, let's define a user_id column on the posts table that references the id column on a users table:
Schema::table('posts', function (Blueprint $table) {
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
});
Since this syntax is rather verbose, Laravel provides additional, terser methods that use convention to provide a better developer experience. The example above could be written like so:
Schema::table('posts', function (Blueprint $table) {
$table->foreignId('user_id')->constrained();
});
Source: https://laravel.com/docs/7.x/migrations
You should create a new migration file let's say 'add_user_foreign_key.php'
public function up()
{
Schema::table('lists', function(Blueprint $table)
{
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('lists', function(Blueprint $table)
{
$table->dropForeign('user_id'); //
});
}
The run
php artisan migrate
If you want to add onDelete('cascade') on the existing foreign key, just drop the indexes and create them again:
public function up()
{
Schema::table('lists', function($table)
{
$table->dropForeign('lists_user_id_foreign');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
public function down()
{
Schema::table('lists', function($table)
{
$table->dropForeign('lists_user_id_foreign');
$table->foreign('user_id')->references('id')->on('users');
});
}
Schema::table('posts', function (Blueprint $table) {
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
});
for versions before 7x;
Schema::create('lists', function(Blueprint $table) {
$table->increments('id');
$table->string('title', 255);
$table->unsignedBigInteger('user_id')->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
for version 7+;
Since this syntax is rather verbose, Laravel provides additional, terser methods that use conventions to provide a better developer experience. When using the foreignId method to create your column, the example above can be rewritten like so:
Schema::create('lists', function(Blueprint $table) {
$table->increments('id');
$table->string('title', 255);
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->timestamps();
});
The foreignId method is an alias for unsignedBigInteger while the constrained method will use convention to determine the table and column name being referenced. If your table name does not match the convention, you may specify the table name by passing it as an argument to the constrained method:
Schema::create('lists', function(Blueprint $table) {
$table->foreignId('user_id')->constrained('users')->onDelete('cascade');
});
source: https://laravel.com/docs/7.x/migrations#foreign-key-constraints
Clear and new in laravel
$table->foreignId('book_id')->constrained();
I was doing the same but got error " id not exist" => so I changed my migration file as below :
question table migration content:
$table->id() => should change to $table->increments('id')
definitions of foreign key in Reply table:
$table->foreign('question_id')->references('id')->on('questions')->onDelete('cascade');
now your foreign key will work.
Clear, modern and Straightforward approach
suppose parent: `Book Model` and `books table`
suppose child : `Page Model` and `pages table`
$table->foreignId('book_id')->references('id')->on('books');
where book_id is is the colomn name in child (pages table)
and id is the linkage between the Parent and Child tables, books and pages tables, and books is the table name to which we are going to link

Resources