Laravel 5 Eloquent bidirectional foreign key migrations - laravel-5

I've and interesting scenario, I would like to implement in Laravel 5. I have 2 tables.
Users ( Holds the sites users )
Media ( Holds the sites images, documents, svg-s, etc... )
My technical constraints are:
Every user has a profile picture and only one profile picture
Every media has an Author
These contraints I interpret as logical columns on
Users table has a column
- profile_image_id (reference to the Media table id column)
Media table has a column
- author_id (reference to the Users table id column)
This works out well, but becomes problematic when I want to use artisan migrations.
my migrations run in this order
Migrating USERS table
Migrating MEDIA table
My migrations have foreign keys being set as
USERS MIGRATION
$table->foreign('profile_image_id')->references('id')->on('media')->onDelete('restrict')->onUpdate('cascade');
MEDIA MIGRATION
$table->foreign('author_id')->references('id')->on('users')->onDelete('restrict')->onUpdate('cascade');
The command I use is
php artisan migrate:refresh --seed
The problem is that when creating the users table, the media table doesn't exist as of yet. And when trying to add the foreign key relation to media table, it produces a SQL error that the media table doesn't exist.
What I did?
I created a function on Users table migration that I ran after the seeding functions had finished
/**
* Veyzon
*
* To be run after the regular run functions on all tables
* have run
*/
public static function delayed_up() {
Schema::table('users', function (Blueprint $table) {
$table->foreign('profile_image_id')->references('id')->on('media')->onDelete('restrict')->onUpdate('cascade');
});
}
This worked out fine and dandy, but when remigrating, then Media table will not delete due to the fact that the user table still has records, where there are profile_image_id-s with values.
Now I thought I will add a few lines of code to the Media tables "down" function, that will set all the USERS table profile_media_id-s to null, but I don't really like this as this seems to tie my separate migration files together and when I declare this as architecturally normal, then this will become a bad practice.
What would you guys do, to create bidirectional One-to-One foreign key relations and integrate them into Laravel migrations?

Easy way to make foriegn key in laravel
public function up()
{
Schema::create('bank_user_details', function (Blueprint $table) {
$table->foreign('country')->references('id')->on('country')
->onUpdate('cascade')->onDelete('cascade');
});
}

Related

Is there an error of Laravel migrations when creating a pivot table?

I have this Laravel's migration create Shema for an standard pivot table:
Schema::create('c_l', function (Blueprint $table) {
$table->foreignId('country_id')->constrained()->onDelete('cascade');
$table->foreignId('language_id')->constrained()->onDelete('cascade');
$table->unique(['country_id', 'language_id']);
});
That creates the «c_l» pivot table, but when I go to check the table structure in phpMyAdmin (Maria DB), I get the following:
Where I am missing «c_l_country_id_foreign» in the indexes section.
So I go to check the relations view, where I find:
It seems that both FKs are present.
I am wondering if this difference
is some kind of presentation issue of phpMyadmin with no effects in
operation, or if instead,
can result in a hidden non-checking of the «country_id» FK
constraint, or
can slow down when fetching the database by «country_id», or
other
Thanks for your help in advance!

Migration tables with different level

When I have tables with relationship (parent and child table) can I migrate them together at once or I need to migrate the child first?
You can't migrate two tables at once, the code won't run in parallel processing
And migrating the child first will cause an error
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1005 Can't create table database.child (errno: 150 "Foreign key constraint is incorrectly formed")
So you have to migrate the parent first
For example, imagine a User has a Pet (domestic animal)
We would have users table and a pets table setup
Schema::create('pets', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
If the filename for the pets migration is
2013_11_06_151235_create_pets_table.php
And the filename for the users migration is
2014_10_12_000000_create_users_table.php
You would get the error above, so you have to rename the pets table migration file to a date later than the one of users
for example
2015_11_06_151235_create_pets_table.php
Because Laravel will try to create a database table with a column referencing a column in a table that doesn't exist yet
Hope this helps
If you don't have foreign key constraints, then you can migrate in any order. If you do have a Foreign Key (FK) however, then it depends on your scheme, also then you could benefit from specifying ON UPDATE and ON DELETE rules to your tables. See the mysql docs for that.

Laravel Model - should I cast foreign index integer keys?

When I make a new table in Laravel, I generally use the Laravel default id column definition: $table->bigIncrements('id'); Say for example I have a clients table with that in my migration.
If I need a foreign relationship on another table, I 'll do it like this:
$table->unsignedBigInteger('client_id');
$table->foreign('client_id')
->references('id')->on('clients')
->onDelete('cascade');
However, if I get model instances of both of those tables and render them with ->toJson();, the id of the first table will be an integer in JSON, while the client_id of the second table will be a string in the json output.
Now I can make a $casts=[] array in the Model class for the second table to cast it to an integer, but I don't know if there's any reason I shouldn't do that. Or maybe I should ALWAYS do that. Is there any guidelines or suggestions about this sort of thing?

How to create a column in laravel database without losing data

Suppose I have a table named "foo" with data and also contains foreign key. Now I want to create a column named "description" in this table. Without reset or rollback how to migrate this table?? Because If I reset or rollback the table then all data will be lost.
As per the docs, you just need to create a separate migration to create the new column.
Create the migration
php artisan make:migration add_description_to_foo
Then just set the migration up with the details you want to add, e.g:
Schema::table('foo', function ($table) {
$table->text('description');
});
Then you can just migrate it:
php artisan migrate
This will allow you to add a column without resetting or rolling back your tables, and thus prevent you from losing your data.
Let's start with your schema. Your table name is foo. You want to add a description column to your foo table without losing existing data. You need to create a new migration for this change.
php artisan make:migration add_columns_to_foo_table --table=foo
A new migration file will be created in your migrations directory. Open it and change it like this:
Schema::table('foo', function ($table) {
$table->text('description');
});
Save it and then run
php artisan migrate
description column will be created immediately without losing your old data as last column. In case you want to reposition your description column you need to use after (in case of MySQL) like this:
Schema::table('foo', function ($table) {
$table->text('description')->after('another_column');
});
Hope you got it.
You will find more details here: https://laravel.com/docs/5.3/migrations#creating-columns

Creation of table columns using artisan migration

Using artisan migrate command, i am trying to create the table. users table is created but not the columns. What could I check ?
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration {
public function up()
{
Schema::create('users', function($table)
{
$table->increments('id');
$table->string('email');
$table->string('password');
$table->timestamps();
});
}
Upon running the above migration file, the table and its columns are successfully created in the database. If you see that the users table is created but not the columns in it, then you might not be looking properly.
I am writing the following answer on my assumption that you're very new to web development also and might not be acquainted with the tools yet.
I assume you're using phpMyAdmin to view your database. If you go to your database and then the users table, you'll be in the Browse tab. Of course, it will be empty because there are no data inserted in the users table, but if you click the Structure tab, then you can view the schema of your users table and see that the columns are created.

Resources