i am creating a fresh application on laravel and i am writing the migrations and i want to set the foreign key for my columns so i am doing like below :
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->integer('type_id');
$table->string('name');
$table->integer('status_id')->default(0);
$table->integer('category_id')->default(0);
$table->integer('store_id');
$table->timestamps();
$table->foreign('status_id')->references('id')->on('product_statuses');
$table->index('status_id');
$table->foreign('type_id')->references('id')->on('product_types');
$table->index('type_id');
$table->foreign('category_id')->references('id')->on('product_categories');
$table->index('category_id');
$table->foreign('store_id')->references('id')->on('stores');
$table->index('store_id');
but these are not working as i check it in phpmyadmin
it let me insert any number not the item from status_id
for example and when i check it in design
tab i dont see the relation between the tables.
#EDIT
adding the product_types
migration :
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('product_types', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
and about the engine i am using wamp with mysql v8 which i think it sups the fk feature
2
Answers
When creating a new table in Laravel. The migration will be generated like:
your table should be:
$table->increments(‘id’);
Instead of (in older Laravel versions):
$table->id();
As you stated in the comments:
Your DB default engine is MyISAM which does not support relational features.
To fix that you can edit your
config/database.php
file, search formysql
entry and change:to
Then you’ll have to recreate the tables.
If you can’t drop and recreate the tables for any reason, you can create a new migration to alter the existing tables. Ie:
Another thing, it’s the data type of the foreign keys columns must match the same data type of the related column.
Since
$table->id()
is an alias of$table->bigIncrements('id')
as stated in laravel latest versión docs, you should use:Also note the order: create the column first, and the the fk reference (and not the inverse).
Reference: https://laravel.com/docs/8.x/migrations#foreign-key-constraints